代码之家  ›  专栏  ›  技术社区  ›  Alexander Tsepkov

Swift 2中“init”与可选参数的使用不明确

  •  3
  • Alexander Tsepkov  · 技术社区  · 9 年前

    我刚刚将我的代码从Swift 1.2更新到Swift 2.1。该项目与以前版本的Swift完全兼容,但现在我看到了“不明确使用‘init’”错误。每次出现此错误似乎都是由构造函数中使用可选参数引起的。我甚至设法在Xcode Playground中使用相同的模式用以下简化代码重现了这个问题:

    class Item : UIView {
        override init(frame: CGRect = CGRectZero) {
            super.init(frame: frame)
        }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    let i = Item()             # Ambiguous use of 'init(frame:)'
    

    然而,我仍然不明白为什么Swift 2.1现在有这个模式的问题,或者替代方案应该是什么。我尝试过搜索这个,但我偶然发现的是由于方法重命名或签名更改而导致的其他(非构造函数)方法的“模糊使用”错误,这里都不是这样。

    1 回复  |  直到 9 年前
        1
  •  4
  •   Witterquick    9 年前

    它的用法不明确,因为当你调用let i=Item()时,有两个选项- init(帧:CGRect=CGRectZero)和init()

    最好这样做:

    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    convenience init() {
        self.init(frame: CGRectZero)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }