@objc public convenience init(size: CGSize, name: String? = nil, address: Address? = nil, order: [Item] = [], phone: String? = nil) {
self.init(size: size, name: name, address: address, order: order)
self.phone = phone
}
@objc public required init(size: CGSize, name: String? = nil, address: Address? = nil, order: [Item] = []) {}
方便的初始化器在上面的代码中调用所需的初始化器。在我的测试中,我尝试调用
let object = ClassA(size: .zero)
我希望看到编译器抱怨多义性,因为两个初始化器都可以以这样的方式调用。但是,它实际上会编译并调用required
初始化器。但是为什么呢?为什么在这种情况下没有歧义?
发布于 2020-07-01 03:36:09
不带参数的函数被认为是比参数带有默认值的函数更好的匹配。比较:
func f(_ arg: String = "") { print("unary") }
func f() { print("nullary") }
f()
输出:
nullary
如果两个函数都有带有默认值的参数,这是不明确的:
func f(_ arg: String = "") { print("string") }
func f(_ arg: Int = 1) { print("int") }
f()
输出:
error: Untitled Page 2.xcplaygroundpage:4:1: error: ambiguous use of 'f'
f()
^
Untitled Page 2.xcplaygroundpage:2:6: note: found this candidate
func f(_ arg: String = "") { print("string") }
^
Untitled Page 2.xcplaygroundpage:3:6: note: found this candidate
func f(_ arg: Int = 1) { print("int") }
^
https://stackoverflow.com/questions/62668719
复制相似问题