Swift,通用函数:为什么需要一个参数标签,而另一个不需要?

Swift, generic function: Why is one argument label needed, the other is not?

Swift游乐场有这个功能:

func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] {
    var result = [Item]()
    for _ in 0..<numberOfTimes {
         result.append(item)
    }
    return result
}
let strArray: [String] = repeatItem("knock", numberOfTimes:4) //!!!!

为什么函数调用中有一个 numberOfTimes:,为什么删除它会给我错误 "missing argument label"?更令人困惑的是,为什么向 "knock" 添加参数标签会给我 "extraneous argument label"?

编辑:

此外,这段代码在调用中没有参数标签:

func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
   return false
}
anyCommonElements([1, 2, 3], [3])

func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] 是一个有两个参数的方法,第一个是item,第二个是numberOfTimes。 在 Swift 中,当您调用方法或函数时,您必须写下参数名称,后跟“:”及其值。

在Swift中第一个参数的名字可以省略

问题一

这是 Swift 的构造。来自 Swift language guide for functions - Function Parameter Names

By default, the first parameter omits its external name, and the second and subsequent parameters use their local name as their external name. All parameters must have unique local names. Although it’s possible for multiple parameters to have the same external name, unique external names help make your code more readable.

...

If you do not want to use an external name for the second or subsequent parameters of a function, write an underscore (_) instead of an explicit external name for that parameter.

请注意,您可以通过在第二个(及以后的)参数名称前放置下划线 _ 来取代此要求。在你的情况下:

func repeatItem<Item>(item: Item, _ numberOfTimes: Int) -> [Item] { ...

最后请注意,这与泛型无关,但通常与 Swift 函数有关。


问题二

尝试更换您的线路

let strArray: [String] = repeatItem("knock", numberOfTimes:4) //!!!!

let strArray = [String](count: 4, repeatedValue: "knock")

这对具有重复条目的数组对象使用初始化程序。