Optional Int in Realm Optional Int in Realm swift swift

Optional Int in Realm


From the Realm docs:

String, NSDate, and NSData properties can be declared as optional or non-optional using the standard Swift syntax.

Optional numeric types are declared using RealmOptional:

class Person: Object {    // Optional string property, defaulting to nil    dynamic var name: String? = nil    // Optional int property, defaulting to nil    // RealmOptional properties should always be declared with `let`,    // as assigning to them directly will not work as desired    let age = RealmOptional<Int>()}let realm = try! Realm()try! realm.write() {    var person = realm.create(Person.self, value: ["Jane", 27])    // Reading from or modifying a `RealmOptional` is done via the `value` property    person.age.value = 28}

RealmOptional supports Int, Float, Double, Bool, and all of the sized versions of Int (Int8, Int16, Int32, Int64).

UPDATE:

The Optional Ints that were mentioned in the Tweet by Realm were just regarding a bugfix for the RealmOptional way of implementing an Optional numeric value with the sized versions of Int

According to the guys from Realm you still have to use RealmOptional if you want to have Optional numeric values in a Realm object. You cannot simply use it like other Optional types.

So dynamic var reps: Int? will not work.


In the case objective c, we can use optional like this

Optional numbers can be stored using an NSNumber * property which is tagged with the type of the number.You can use NSNumber <RLMInt> *, NSNumber<RLMBool> *, NSNumber<RLMFloat> *, and NSNumber<RLMDouble> *.

Please just refer the example code

@interface OptionalTypes : RLMObject@property NSString *optionalString;@property NSString *requiredString;@property NSData *optionalData;@property NSDate *optionalDate;@property NSNumber<RLMInt> *optionalInt;@property NSNumber<RLMBool> *optionalBool;@property NSNumber<RLMFloat> *optionalFloat;@property NSNumber<RLMDouble> *optionalDouble;@end@implementation OptionalTypes+ (NSArray *)requiredProperties {    return @[@"requiredString"];}@end

For more info you can also check this link:https://realm.io/blog/realm-objc-swift-0-96-0/