Swift尾随闭包无法编译

时间:2019-02-24 02:43:16

标签: swift

我试图将一组键值对(元组)转换成字典:

let pairs = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]

let firstValues = Dictionary( pairs,
    uniquingKeysWith: { (first, _) in first }
)
// ["b": 2, "a": 1]

但是当我尝试使用结尾闭包语法时,代码只是无法编译,为什么?

// ⛔️ error: contextual closure type '(_, _) -> _' 
//    expects 2 arguments, but 1 was used in closure body
let firstValues2 = Dictionary( pairs ) { $0 }

1 个答案:

答案 0 :(得分:2)

There is nothing to do with the trailing closure syntax.

If you try the code below it will complain as well:

let firstValues = Dictionary(pairs, uniquingKeysWith: { $0 })

The compiler is complaining that you are not using the new value. You have a few ways to go around.

1) give the values a name:

let firstValues1 = Dictionary(pairs) { oldValue, newValue in oldValue }

2) you can also ignore the value using an underscore

let firstValues2 = Dictionary(pairs) { oldValue, _ in oldValue }

3) make any type of use of the old value as well as the new value. A simple print would suffice the compiler.

let firstValues3 = Dictionary(pairs) {
    print($1)
    return $0
}