为什么我不能在 Xcode 9.2 中对数组文字调用 reduce(into:)?

Why can't I call reduce(into:) on an array literal in Xcode 9.2?

我正在寻找一种将数组映射到字典的方法,并找到了这个 。这很有帮助。我将 post 中的代码复制到 playground 中并且它有效。

然后我决定多玩玩它:

[1,2,3].reduce(into: [Int: String](), {[=11=][] = .description})

我预计它会 return [1: "1", 2: "2", 3: "3"] 但出现编译器错误:

Cannot subscript a value of incorrect or ambiguous type

我试图减少到一个数组:

[1,2,3].reduce(into: [Int](), {[=12=].append()}) // I am aware that this is pointless

但是还是编译不通过。这次消息不同:

Type of expression is ambiguous without more context

然后我发现这是因为我使用的是数组文字,因为如果我先声明一个常量数组,然后在其上调用reduce,不会出现错误:

let arr = [1,2,3]
arr.reduce(into: [Int: String](), {[=13=][] = .description})

正常的 reduce 似乎可以很好地处理文字:

[1,2,3].reduce(0, +)

为什么 reduce(into:) 不适用于数组文字?

这是一个错误:SR-6995 Unable to infer type with reduce(into:) 已在 同时,Xcode 9.3.1.

不会再出现该错误

有趣的是,添加 any 附加语句就足够了 使其在 Xcode 9.2:

中编译的闭包
let d = [1,2,3].reduce(into: [Int: String](), {
    () ; [=10=][] = .description
})

另一种选择是在闭包中指定累加器类型 明确地:

let d = [1,2,3].reduce(into: [Int: String](), { (accum: inout [Int: String], elem) in
    accum[elem] = elem.description
})

或者,正如@vacawama 注意到的那样,显式注释数组类型:

let d = ([1,2,3] as [Int]).reduce(into: [Int: String](), {
    [=12=][] = .description
})