【问题标题】:Is there a function or method Array.reduce in swift? [closed]swift中有函数或方法Array.reduce吗? [关闭]
【发布时间】:2020-02-16 13:42:11
【问题描述】:

我想使用内置的 array.reduce 闭包方法将字符串数组缩减为单个字符串。

我知道使用 join 方法更容易。只是想看看有没有办法?

【问题讨论】:

    标签: arrays swift reduce


    【解决方案1】:

    是的,您可以使用数组中的 reduce 方法。

    let arr = ["hello", "world"]
    let result = arr.reduce("") { (prev, curr) -> String in
        return prev + curr
    }
    // even shorter method
    let result2 = arr.reduce("") {$0 + $1} // arr.reduce("", +) will produce the same result
    
    print(result) // Prints "Hello world"
    print(result2) // "Hello world"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 2016-12-22
      • 1970-01-01
      • 2020-09-06
      相关资源
      最近更新 更多