功能 Swift returns 错误

Functional Swift returns error

为什么 r1 可以工作但 r2 会抛出编译错误(无法使用类型为“(NSArray, [Int])”的参数列表调用“+”)?

func reduce<T1, T2>(input:[T1], initialResult: T2, f:(T2, T1) -> T2) -> T2 {
    var result = initialResult
    for x in input {
        result = f(result, x)
    }
    return result
}

let array2D = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

let r1 = reduce(array2D, []){result, x in
    result + x}

let r2 = reduce(array2D, []){result, x in
    return result + x}

如果您指定 return 类型,它会消除此错误,例如:

let r3 = reduce(array2D, []){result, x -> [Int] in
    return result + x}

如果您指定初始空数组是一个 Int 数组,错误将被消除:

let r4 = reduce(array2D, [Int]()){result, x in
    return result + x}