斯威夫特 3.0
在 Swift 3.0 中,slated to be released in late 2016,默认行为很简单:
您可以在Swift API Design Guidelines 中最简洁地找到这些规则。这个最新的行为在SE-0056, "establish consistent label behavior across all parameters including first labels," 中提出并在SR-961 中实现。默认行为可以按照下面“覆盖默认行为”中的描述进行更改。
斯威夫特 2.2
在 Swift 2.2 中,语言对外部参数标签的默认设置已经改变,现在更简单了。默认行为可以总结如下:
- 方法和函数的第一个参数不应有外部参数标签。
- 方法和函数的其他参数应该有外部参数标签。
- 初始化器的所有参数都应该有外部参数标签。
默认行为可能会按照下面“覆盖默认行为”中的说明进行更改。
一个例子
这些规则最好用一个例子来说明:
func printAnimal(animal: String, legCount: Int) {
let legNoun = legCount == 1 ? "leg" : "legs"
print("\(animal) has \(legCount) \(legNoun)")
}
struct Player {
let name: String
let lives: Int
init(name: String, lives: Int) {
self.name = name
self.lives = lives
}
func printCurrentScore(currentScore: Int, highScore: Int) {
print("\(name)'s score is \(currentScore). Their high score is \(highScore)")
}
}
// SWIFT 3.0
// In Swift 3.0, all argument labels must be included
printAnimal(animal: "Dog", legCount: 4)
let p = Player(name: "Riley", lives: 3)
p.printCurrentScore(currentScore: 50, highScore: 110)
// SWIFT 2.2
// In Swift 2.2, argument labels must be included or omitted in exactly the following way
// given the definition of the various objects.
printAnimal("Dog", legCount: 4)
let p = Player(name: "Riley", lives: 3)
p.printCurrentScore(50, highScore: 110)
// In Swift 2.2, none of the following will work
printAnimal(animal: "Dog", legCount: 4) // Extraneous argument label 'animal:' in call
let q = Player("Riley", lives: 3) // Missing argument label 'name:' in call
p.printCurrentScore(50, 110) // Missing argument label 'highScore:' in call
覆盖默认行为
对于任何方法或函数的任何参数,您都可能偏离语言的默认值,尽管样式指南正确地警告您不要这样做,除非有充分的理由。
要在通常没有的地方添加一个外部参数标签——仅适用于 Swift 2.2,因为 Swift 3.0 默认为每个参数分配外部标签——或者更改一个外部参数标签——适用于两个版本——编写本地参数标签之前的所需外部参数标签:
func printAnimal(theAnimal animal: String, legCount: Int) {
let legNoun = legCount == 1 ? "leg" : "legs"
print("\(animal) has \(legCount) \(legNoun)")
}
printAnimal(theAnimal: "Dog", legCount: 4)
要删除通常会有的外部参数标签,请使用特殊的外部参数标签_:
func printAnimal(animal: String, _ legCount: Int) {
let legNoun = legCount == 1 ? "leg" : "legs"
print("\(animal) has \(legCount) \(legNoun)")
}
// SWIFT 3.0
printAnimal(theAnimal: "Dog", 4)
// SWIFT 2.2
printAnimal("Dog", 4)
这些“默认覆盖”适用于任何方法或函数,包括初始化程序。