class User {
var id: Int!
init(data: JSON){
id = data["id"].int
//if id doesn't exist, then cancel the init and return nil.
}
}
我想通过将 JSON 传递给其构造函数来初始化用户。但是,有时 JSON 不匹配。在这种情况下,我希望取消初始化,并且 User 为零。
最佳答案
像这样:
class User {
var id: Int!
init?(data: JSON) {
guard let id = Int(data["id"]) else {
return nil
}
self.id = id
}
}
关于swift - 如何在 init() 期间取消对象的初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36272141/