Swift 中重复使用的关键字是什么?
What is the keyword repeating used for in Swift?
我正在阅读 "The Swift Programming Language (Swift 4.2)" 官方书籍,在 Swift Tour/Generics 部分,我遇到了以下代码
func makeArray1<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
let arr1 = makeArray1(repeating: "knock", numberOfTimes: 4)
print(arr1)
打印出来
["knock", "knock", "knock", "knock"]
我对函数 makeArray1 定义中单词 'repeating' 的作用感到困惑。我尝试使用以下代码 运行 没有那个词的代码
func makeArray2<Item>(item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
let arr2 = makeArray2(item:"knock", numberOfTimes:4)
print (arr2)
并且代码给出了与之前相同的结果。
["knock", "knock", "knock", "knock"]
那么代码中'repeating'有什么用呢?
它不是关键字,它是一个可选的函数参数标签,可以与 function/method 中使用的局部参数名称不同。
阅读 Swift 编程语言中的 Function Argument Labels and Parameter Names 部分:
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label. …
You write an argument label before the parameter name, separated by a space …
If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.
我正在阅读 "The Swift Programming Language (Swift 4.2)" 官方书籍,在 Swift Tour/Generics 部分,我遇到了以下代码
func makeArray1<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
let arr1 = makeArray1(repeating: "knock", numberOfTimes: 4)
print(arr1)
打印出来
["knock", "knock", "knock", "knock"]
我对函数 makeArray1 定义中单词 'repeating' 的作用感到困惑。我尝试使用以下代码 运行 没有那个词的代码
func makeArray2<Item>(item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
let arr2 = makeArray2(item:"knock", numberOfTimes:4)
print (arr2)
并且代码给出了与之前相同的结果。
["knock", "knock", "knock", "knock"]
那么代码中'repeating'有什么用呢?
它不是关键字,它是一个可选的函数参数标签,可以与 function/method 中使用的局部参数名称不同。
阅读 Swift 编程语言中的 Function Argument Labels and Parameter Names 部分:
Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label. …
You write an argument label before the parameter name, separated by a space …
If you don’t want an argument label for a parameter, write an underscore (_) instead of an explicit argument label for that parameter.