swift:无法将[sic]字符数组减少为字符串

时间:2015-04-15 20:28:17

标签: swift functional-programming

我意识到这是一个不必要的问题,但是......为什么我不能使用reduce将字符数组转换为字符串?

如,

let str = "this is a string"
let clist = Array(str)
let slist = clist.reduce("", +)

告诉我:'Character'不是'Uint8'的子类型 什么时候

list dlist = [0, 1, 2, 3, 4, 5, 6]
let sum = dlist.reduce(0, +)

作品

我知道我可以简单地做slist = String(clist),但我只是想知道,你知道吗?

Swift 1.1在xcode 6.2的操场上

谢谢!

2 个答案:

答案 0 :(得分:2)

combine:关闭

let slist = clist.reduce("", +)
  • $0是迄今累积的结果 - String
  • $1是来自clist的当前元素 - Character

没有+运算符将(String, Character)作为参数。

这样可行:

let slist = clist.reduce("") { $0 + String($1) }

答案 1 :(得分:1)

在Swift 1.2中:

let str = "this is a string"
let clist = Array(str)
let slist = clist.map { String($0) }.reduce("", combine: { $0 + $1 })
println(slist) // "this is a string"
相关问题