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

标签 swift object-initializers

使用以下代码,我尝试定义一个简单的模型类及其可失败初始化程序,它采用 (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/

相关文章:

ios - 尝试在 Swift 3 中保存自定义对象时尝试插入非属性列表对象

ios - DispatchQueue.main.async {} 在 vi​​ewDidLoad

ios - 如何使用 protected init 来模拟对象

c#-3.0 - 如何在 Resharper 中更改 "Use Object Initializer"重构的格式?

ios - 使用 UIVisualEffectView 创建模糊 View ,在模拟器上正确但在 iphone 和 ipad 上不正确

F# 中的 C# 对象初始化语法

c# - 使用对象初始化器 - Resharper 建议

c# - 初始化语法

方法内的Java空 block 与其他 block 不同?

swift - 如何在 Swift SpriteKit 中添加固定背景