gpt4 book ai didi

swift - 在 Swift 中实现可失败初始化器的最佳实践

转载 作者:可可西里 更新时间:2023-10-31 23:44:31 25 4
gpt4 key购买 nike

使用以下代码,我尝试定义一个简单的模型类及其可失败初始化程序,它采用 (json-) 字典作为参数。如果原始 json 中未定义用户名,则初始化程序应返回 nil

1.为什么代码不编译?错误消息说:

All stored properties of a class instance must be initialized before returning nil from an initializer.

这没有意义。当我计划返回 nil 时,为什么要初始化这些属性?

2。我的方法是否正确,或者是否有其他想法或通用模式可以实现我的目标?

class User: NSObject {

let userName: String
let isSuperUser: Bool = false
let someDetails: [String]?

init?(dictionary: NSDictionary) {
if let value: String = dictionary["user_name"] as? String {
userName = value
}
else {
return nil
}

if let value: Bool = dictionary["super_user"] as? Bool {
isSuperUser = value
}

someDetails = dictionary["some_details"] as? Array

super.init()
}
}

最佳答案

That doesn't make sense. Why should I initialize those properties when I plan to return nil?

根据 Chris Lattner 的说法,这是一个错误。他是这样说的:

This is an implementation limitation in the swift 1.1 compiler, documented in the release notes. The compiler is currently unable to destroy partially initialized classes in all cases, so it disallows formation of a situation where it would have to. We consider this a bug to be fixed in future releases, not a feature.

Source

编辑:

So swift 现在是开源的并且根据 this changelog它现在已在 swift 2.2 的快照中修复

Designated class initializers declared as failable or throwing may now return nil or throw an error, respectively, before the object has been fully initialized.

关于swift - 在 Swift 中实现可失败初始化器的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32850974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com