Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic optional properties in Swift 2.0

I have seen this post Optional dynamic properties in Swift but I don't want to have to wrap up the class in an NSObject. This just is concerning the Realm database I don't have to have nil properties but it would be a nice way I think to model my database. In the Realm documentation which can be found here https://realm.io/docs/swift/latest/ it says optionals are supported. Here is my

Code

dynamic var complete: Bool? = nil

and here is my

Error

Property cannot be marked dynamic because its type cannot be represented in Objective-C

I know this is the same code and error as the post above but I am just curious if the Realm documentation says it supports it do they have another work around?

like image 212
Cody Weaver Avatar asked Oct 19 '15 03:10

Cody Weaver


1 Answers

From the docs on supported types and optional properties.

String, NSDate, NSData and Object properties can be optional. Storing optional numbers is done using RealmOptional.

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

So optionals are supported for String, NSDate, NSData and Object types nicely with the standard swift syntax.

For other numeric types (such as Bool) that is done with RealmOptional. Then to use a variable of this RealmOptional type you access its value property, which is an optional that represents your underlying value.

// definition (defined with let)
let complete = RealmOptional<Bool>()  // defaults to nil
// usage
complete.value = false  // set non-nil value
...
complete.value = nil    // set to nil again
like image 176
Edman Avatar answered Nov 06 '22 20:11

Edman