为什么 Swift 的 reduce 函数在正确定义所有类型时抛出 'Type of expression ambigious without more context' 错误?

Why does Swift's reduce function throw an error of 'Type of expression ambigious without more context' when all types are properly defined?

var nums = [1,2,3]

let emptyArray : [Int] = []
let sum1 = nums.reduce(emptyArray){ [=12=].append()}
let sum2 = nums.reduce(emptyArray){ total, element in
    total.append(element)
}
let sum3 = nums.reduce(emptyArray){ total, element in
    return total.append(element)
}

对于所有三种方法,我都收到以下错误:

Type of expression ambiguous without more context

但是查看 documentation 和 reduce 的方法签名:

func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) rethrows -> Result

可以看到ResultElement都可以正确推断。结果显然是 [Int] 类型,而 Element 是 [Int] 类型。

所以我不确定出了什么问题。我也看到了 但这也无济于事

你是对的,你正在传递要推断的正确类型。 该错误具有误导性

你有没有写:

func append<T>(_ element: T, to array: [T]) -> [T]{
    let newArray = array.append(element)
    return newArray
} 

那么编译器会给出正确的错误:

Cannot use mutating member on immutable value: 'array' is a 'let' constant

现在我们知道正确的错误应该是什么了:

也就是说,Result 和 Element 在闭包中都是不可变的。你必须把它想象成一个普通的 func add(a:Int, b:Int) -> Int,其中 ab 都是不可变的。

如果你想让它工作,你只需要一个临时变量:

let sum1 = nums.reduce(emptyArray){
    let temp = [=11=]
    temp.append()
    return temp
}

还要注意下面的是错误的!

let sum3 = nums.reduce(emptyArray){ total, element in
    var _total = total
    return _total.append(element)
}

为什么?

因为 _total.append(element) 的类型是 Void 它是一个函数。它的类型是 而不是 5 + 3Int[5] + [3] 即 [Int]

的类型

因此你必须做:

let sum3 = nums.reduce(emptyArray){ total, element in
    var _total = total
    _total.append(element)
    return _total
}