Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Realm use RealmOptional<Int> rather than Int? for optional properties?

Tags:

swift

realm

Realm's documentation on optional properties states:

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.

Why do numeric types use the non-standard RealmOptional rather than Swift's built-in optional syntax?

like image 961
bdash Avatar asked Dec 11 '22 20:12

bdash


1 Answers

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.

like image 54
bdash Avatar answered Dec 29 '22 12:12

bdash