swift - 函数式 Swift 返回错误

标签 swift functional-programming

为什么 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}

最佳答案

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

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

如果您指定初始空数组是 Int 数组,则错误会消失:

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

关于swift - 函数式 Swift 返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27741954/

相关文章:

ios - Admob 广告不显示 swift

swift - iOS 10 发布后,我可以使用 Xcode 7.3 提交 Swift 2.2 应用程序吗?

haskell - Monads如何被认为是纯的?

function - 如何计算 Racket 中两个合约的盈亏平衡点

swift - 无法修改用户解析

ios - 具有非标准化数据的 Realm 迁移

functional-programming - 如何在 OCaml 中查找数组元素的索引

haskell - 我怎样才能证明这种类型会被推断出来?

swift - 在 Swift 和 Programrush 中使用 bool 的目的

python-3.x - 函数式编程: How does one create a new column to a dataframe that contains a multiindex column?