领域中的可选Int

时间:2015-10-26 21:58:43

标签: swift int swift2 realm optional

我正在尝试在Realm中使用Optional Int,我想到了一个老错误。

代码

dynamic var reps: Int? = nil

错误

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

我使用Realm 0.96.1和XCode 7.1

我在Realm文档中了解到,Int并不支持Optional,而是https://twitter.com/realm/status/656621989583548416。这是来自Realm twitter,这就是为什么我感到困惑。是Optional Int支持还是不支持?

2 个答案:

答案 0 :(得分:38)

来自Realm docs:

可以使用标准Swift语法将

StringNSDateNSData属性声明为可选属性或非可选属性。

使用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支持IntFloatDoubleBool以及Int的所有大小版本(Int8 },Int16Int32Int64)。

<强>更新

Realm在Tweet中提到的可选Ints只是针对RealmOptional方法实现可选数值的错误修正,其大小版本为Int

According对于来自Realm的人来说,如果你想在Realm对象中拥有可选的数值,你还是必须使用RealmOptional。您不能像其他可选类型一样简单地使用它。

所以dynamic var reps: Int?无效。

答案 1 :(得分:0)

在目标c的情况下,我们可以像这样使用可选

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> *.

请仅参考示例代码

@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

有关更多信息,您还可以检查以下链接: https://realm.io/blog/realm-objc-swift-0-96-0/