简体   繁体   English

领域类型转换问题Swift

[英]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. 我必须声明领域字符串属性以保存从API获得的值,但是问题是,我不知道哪种类型的数据将来自服务器。 Sometimes I am getting String value and sometime Int. 有时我得到String值,有时得到Int。 Now how I will save data to the realm. 现在,我将如何将数据保存到领域。

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

API Response API响应

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

This is the safest (where stringOrInt is the value you're receiving from the API): 这是最安全的方法(其中stringOrInt是您从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 1- Relam对象类

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 1-在您的数据库中测试添加对象

 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 3-结果

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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