Realm's documentation on optional properties states:
String
,NSDate
, andNSData
properties can be declared as optional or non-optional using the standard Swift syntax. Optional numeric types are declared usingRealmOptional
.
Why do numeric types use the non-standard RealmOptional
rather than Swift's built-in optional syntax?
Realm model classes automatically implement getters and setters for your persisted properties that access the underlying database data. In order to provide these getters and setters, your properties must be declared with the dynamic
modifier. This modifier asks Swift to dynamically dispatch accesses to the properties via getters and setters rather than directly accessing the member at compile time. The dynamic
modifier comes with a significant limitation: it is only supported for types that can be represented in Objective-C. This is because Swift's dynamic dispatch is built on top of the Objective-C runtime. It is this limitation that prevents Int?
from being directly supported by Realm.
You may wonder how String?
, NSData?
, and NSDate?
are supported given this limitation. The answer is that they have natural equivalents in Objective-C, namely nullable NSString *
, nullable NSData *
, and nullable NSDate *
. No such equivalents exist for Swift's numeric types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With