Swift 3.1 中初始化参数的参数标签

Argument labels for initialization parameters in Swift 3.1

Apple 的书 “The Swift Programming Language (Swift 3.1)” 陈述如下:

As with function and method parameters, initialization parameters can have both a parameter name for use within the initializer’s body and an argument label for use when calling the initializer.

However, initializers do not have an identifying function name before their parentheses in the way that functions and methods do. Therefore, the names and types of an initializer’s parameters play a particularly important role in identifying which initializer should be called. Because of this, Swift provides an automatic argument label for every parameter in an initializer if you don’t provide one.

我不明白最后一句话,因为在参数 names/labels 方面,我没有注意到 functions/methods 和初始值设定项之间有任何区别。如何为初始化程序自动提供参数标签?

所描述的功能是这样的:给定一个结构:

struct Point {
    let x: Double
    let y: Double
}

Swift会自动生成Point.init(x: Double, y: Double)。如果您在 struct 主定义中添加您自己的 init 方法,那么 Swift 将不会创建该自动 init。 (如果你在扩展中添加一个 init,那么你 得到一个自动 init。这就是为什么人们经常在一个扩展中添加方便 init结构的扩展名。)

最后一段试图表达的观点是 Point(x:y:) 优于 Point(_:_:)。初始化器中的标签甚至比方法名中的标签更有价值,因为所有初始化器都具有相同的 "base" 名称 ("init")。他们只是在解释为什么他们没有选择一些人可能期望来自其他语言的更隐含的默认设置。

简而言之,有时未标记的参数在方法中有意义,这取决于方法的名称是什么以及第一个参数的明确程度。但在init中,未标记的参数应该引起强烈的怀疑。