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") } }
根据build议,我做了variablesdynamicvariablesvar而不是var,并将它们初始化为空string。 最初,我只是init()方便的init()。 添加领域后,方便init()根据build议调用self.init()。 现在默认实现询问抛出
(fatalError("init() has not been implemented")
什么应该在所需的公共init()? 我是否必须重新初始化variables?
正如我在回答你的上一个问题时所提到的,通过切换你的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 } }