RealmSwift:必需的公共init()错误 [英] RealmSwift : required public init() error

查看:96
本文介绍了RealmSwift:必需的公共init()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import RealmSwift
import Realm

public class Card : Object {
    dynamic var username: String = ""
    dynamic var firstName: String = ""
    dynamic var lastName: String = ""

    convenience init?(dictionary: [String:Any]?) {
        guard let dictionary = dictionary , let username =  dictionary["username"] as? String else { return else}
        self.init()
        self.username = username
        self.firstName = firstName 
        self.lastName = lastName
    }

    required public init() {
        fatalError("init() has not been implemented")
    }

    required public init( realm: RLMRealm, schema: RLMObjectSchema) {
        fatalError("init(realm:schema:) has not been implemented")
    }

    required public init( value: Any, schema: RLMSchema) {
       fatalError("init(value:schema:) has not been implemented")
    }
}

根据建议,我将变量设为var而不是var,并将其初始化为空字符串.最初,我拥有init()的便利,就像init()一样.添加领域之后,便利的init()根据建议调用self.init().现在,默认实现会抛出异常

As per suggestions I made the variables dynamic var as opposed to var and initialized them to empty strings. Initially I had the convenience init() as just init(). After adding realm the convenience init() calls self.init() as per suggestions. Now the default implementation asks throws

(fatalError("init() has not been implemented")

所需的公共init()中应该包含什么?我是否必须再次初始化变量?

What should be inside the required public init()? Do I have to initialize the variables again?

推荐答案

正如我在我对您之前的问题的回答中所述,通过将您的init?方法切换到便捷初始化程序,不再需要从超类重写各种必需的初始化程序.您只需从子类中删除三个required public init方法.

As I mentioned in my answer to your previous question, by switching your init? method to a convenience initializer, it's no longer necessary to override the various required initializers from the superclass. You can simply remove the three required public init methods from your subclass.

public class Card : Object {
    dynamic var username: String = ""
    dynamic var firstName: String = ""
    dynamic var lastName: String = ""

    convenience init?(dictionary: [String:Any]?) {
        guard let dictionary = dictionary,
            let username = dictionary["username"] as? String,
            let firstName = dictionary["firstName"] as? String,
            let lastName = dictionary["lastName"] as? String
            else { return nil }

        self.init()

        self.username = username
        self.firstName = firstName
        self.lastName = lastName
    }
}

这篇关于RealmSwift:必需的公共init()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆