RealmSwift : required public init() error

不羁的心 提交于 2019-12-24 07:14:26

问题


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")
    }
}

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")

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


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/44728234/realmswift-required-public-init-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!