RealmSwift:需要公共init()错误

时间:2017-06-23 18:54:51

标签: ios swift realm

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()。现在默认实现抛出

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

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

1 个答案:

答案 0 :(得分:4)

正如我在my answer to your previous question中提到的,通过将init?方法切换为便捷初始化程序,不再需要从超类中覆盖各种所需的初始值设定项。您只需从子类中删除三个required public init方法即可。

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