xcode 在 Swift 2 中模糊使用带有可选参数的“init”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34879251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ambiguous use of "init" with optional arguments in Swift 2
提问by Alexander Tsepkov
I've just updated my code from Swift 1.2 to Swift 2.1. The project was fully-functioning with previous version of Swift, but now I'm seeing "Ambiguous use of 'init'" errors. Each occurrence of this error seems to be caused by the use of optional arguments in the constructor. I've even managed to reproduce this issue in Xcode Playground with the following simplified code using the same pattern:
我刚刚将我的代码从 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:)'
However, I still don't understand why Swift 2.1 now has a problem with this pattern, or what the alternative should be. I've tried searching for this, but all I've stumbled upon was "ambiguous use" errors for other (non-constructor) methods due to method renaming or signature changing, neither of which is the case here.
但是,我仍然不明白为什么 Swift 2.1 现在这种模式有问题,或者替代方案应该是什么。我试过搜索这个,但我偶然发现的是由于方法重命名或签名更改导致的其他(非构造函数)方法的“模糊使用”错误,这两种情况都不是这里的情况。
回答by Roee84
It's ambiguous use because when u call let i = Item(), there are 2 options - the init(frame: CGRect = CGRectZero) and the init()
这是模棱两可的用法,因为当你调用 let i = Item() 时,有 2 个选项 - init(frame: CGRect = CGRectZero) 和 init()
it's better to do something like this:
最好做这样的事情:
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")
}