Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

swift - Optional Int in Realm

I am trying to use an Optional Int in Realm and am getting an old error I think.

Code

dynamic var reps: Int? = nil

Error

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

I am using Realm 0.96.1 with XCode 7.1

I understand in the Realm documentation it says the Int isn't supported as an Optional but https://twitter.com/realm/status/656621989583548416. That is from the Realm twitter so thats why I am confused. Are Optional Int supported or still no?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the Realm docs:

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:

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 supports Int, Float, Double, Bool, and all of the sized versions of Int (Int8, Int16, Int32, Int64).

UPDATE:

The Optional Ints that were mentioned in the Tweet by Realm were just regarding a bugfix for the RealmOptional way of implementing an Optional numeric value with the sized versions of Int

According to the guys from Realm you still have to use RealmOptional if you want to have Optional numeric values in a Realm object. You cannot simply use it like other Optional types.

So dynamic var reps: Int? will not work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...