简体   繁体   中英

Realm Typecast issue Swift

I have to declare realm string property for to save the value get from API, but the issue is, I don't know which type of data will come from the server. Sometimes I am getting String value and sometime Int. Now how I will save data to the realm.

 class Fields: Object {
       @objc dynamic var default_value: String? = nil
    }

API Response

{
  access = 1;
  default_value = " ";
},
{
  access = 1;
  default_value = 20;
}

This is the safest (where stringOrInt is the value you're receiving from the API):

fieldsObject.default_value = stringOrInt as? String

But you can also use string interpolation and inject the value directly into a string literal:

fieldsObject.default_value = "\\(stringOrInt)"

You can try this solution

1- Relam object class

class Fields: Object {
    @objc dynamic private var default_value: String? = nil

    @objc var defaultValue: Any?{
        didSet{
            self.default_value = "\(defaultValue!)"
        }
    }
    open override class func ignoredProperties()->[String] {

        return ["defaultValue"]
    }
}

1- Test add object in you'r DB

 let obj = Fields()
        obj.defaultValue = "ahmad"

        let obj2 = Fields()
        obj2.defaultValue = 1

        let realm = try! Realm()
        try! realm.write {

            realm.add([obj,obj2])
        }

3- Result

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM