简体   繁体   中英

Is there a function or method Array.reduce in swift?

I would like to reduce the array of strings into a single string using the built in array.reduce closure method.

I know using the join method is easier. Just wanted to see if there is a way?

Yes, there is a reduce method in arrays that you can use.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM