swift - 类层次结构中的便利初始化导致无限递归

标签 swift initialization swift2 designated-initializer

我在 Swift 2.0 中有一个包含 2 个类的层次结构。这两个类都可以通过传递参数或传递包含参数的 JSON 字典 ([String: AnyObject]) 来实例化。

直接接受参数的初始化是designated inits,而接受JSON的是convenience inits,具有相同的签名

class Thing {
    let name : String

    init(name: String){
        self.name = name
    }

    convenience init(jsonNamed: String){

        // read the json, parse and extract
        // the name
        self.init(name: "got this from JSON")
    }
}

class SubThing : Thing{

    var surname : String

    init(name: String, surname: String){
        self.surname = surname
        super.init(name: name)
    }


    convenience init(jsonNamed: String){

        self.init(jsonNamed: "got this from JSON")
        // extract surname
        self.surname = "Got this from json"


    }

}

SubThing 中的convenience init 不允许在super 中调用同一个init,如果我在self 中调用它,会导致无限递归,因为两者方法具有相同的签名

如果我让两个 json inits 指定,我就不能在 Thing 中调用 self.init(name:),而且我将不得不在 Thing 的两个初始化程序中重复相同的代码。

解决这种情况的最佳方法是什么?

最佳答案

您正在 SubThing 中执行循环,从自身调用相同的指定初始化程序。我看到它是这样重写的:

class Thing {
    private var name : String?

    private init() {}

    convenience init(name: String){
        self.init()
        self.name = name
    }

    convenience init(jsonNamed: String){
        self.init()
        self.name = getNameFromJSON()
    }

    private func getNameFromJSON() -> String {
        // read the json, parse and extract
        // the name
        return "got this from JSON"
    }
}

class SubThing : Thing {
    private var surname : String?

    convenience init(name: String, surname: String){
        self.init(name: name)
        self.surname = surname
    }


    convenience init(jsonNamed: String){
        self.init()
        self.name = getNameFromJSON()
        // extract surname
        self.surname = "Got this from json"
    }
}

测试和工作。 更新:添加了私有(private)初始化,因此不能初始化为空。

关于swift - 类层次结构中的便利初始化导致无限递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31858526/

相关文章:

ios - 如何设置CAEmitterLayer背景透明?

ios - 在 UIImage 上徒手绘制

java - Java 中的全局代码初始化

c# - 单声道 2.6.7 : Array Initializer Bug?

c++ - 向类的构造函数添加虚拟参数以解决调用歧义是否违反任何规则?

ios - iPhone 应用程序出现奇怪的崩溃

swift - 如何在 UICollectionView 中加载列数

ios - 应用审查小组的 EXC_BREAKPOINT (SIGTRAP)。不可复制

ios - 带有通知问题的 Swift 暂停和重新创建计时器

ios - Realm + Swift 使用 JSON 字符串更新对象