iOS

iOS) Realm Numeric Optional

삼쓰 웅쓰 2020. 2. 28. 09:06
728x90
Property cannot be marked @objc because its type cannot be represented in Objective-C

다음과 같은 에러가 발생한다면 숫자를 optional로 생성하려고 한 것은 아닌지 확인해보셔야 합니다.

String, Date, Date는 표준 Swift 문법을 따르면되지만,

Int, double과 같은 numeric 타입들은 단순히 Int? Double? 와 같은 optional 타입으로 하면 안되고 RealmOptional<T>() 타입을 사용해서 RealmOptional 변수의 value 프로퍼티를 이용해야합니다. 그리고 @objc dynamic var 가 아니라 let 을 사용합니다.

realm document 에는 다음과 같이 나와있습니다.


Required properties

 

String, Date, and Data properties can be declared as optional or required (non-optional) using standard Swift syntax. Optional numeric types are declared using the RealmOptional type:

class Person: Object {
    // Optional string property, defaulting to nil
    @objc 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).


보기쉽게 다음 표를 참고하시면 좋을 것 같습니다.

 

감사합니다 :)