为什么Realm使用RealmOptional< Int>而不是诠释?可选属性? [英] Why does Realm use RealmOptional<Int> rather than Int? for optional properties?
问题描述
Realm的有关可选属性的文档指出:
可以使用标准Swift语法将
String
,NSDate
和NSData
属性声明为可选或非可选属性.可选的数字类型使用RealmOptional
声明.
String
,NSDate
, andNSData
properties can be declared as optional or non-optional using the standard Swift syntax. Optional numeric types are declared usingRealmOptional
.
为什么数字类型使用非标准的RealmOptional
而不是Swift的内置可选语法?
Why do numeric types use the non-standard RealmOptional
rather than Swift's built-in optional syntax?
推荐答案
领域模型类为访问基础数据库数据的持久属性自动实现getter和setter.为了提供这些getter和setter,必须使用dynamic
修饰符声明属性.这个修饰符要求Swift通过getter和setter动态分配对属性的访问,而不是在编译时直接访问成员. dynamic
修饰符有一个明显的局限性:仅支持可以在Objective-C中表示的类型.这是因为Swift的动态调度是在Objective-C运行时之上构建的.正是这种限制阻止了Realm直接支持Int?
.
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.
您可能想知道在给定此限制的情况下如何支持String?
,NSData?
和NSDate?
.答案是它们在Objective-C中具有自然等效项,即nullable NSString *
,nullable NSData *
和nullable NSDate *
. Swift的数字类型不存在此类等效项.
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.
这篇关于为什么Realm使用RealmOptional< Int>而不是诠释?可选属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!