addObjectsFromArray错误:如何将`Array <character>`转换为`[AnyObject]`?

时间:2016-07-14 03:44:30

标签: arrays swift

我想将String转换为Array,然后按NSCountedSet计算重复值。

这些代码出错:

    let str = "hello"
    let ar = Array(str.characters)
    let set = NSCountedSet()
    set.addObjectsFromArray(ar)

错误:

 error: cannot convert value of type 'Array<_Element>' (aka 'Array<Character>') to expected argument type '[AnyObject]'
    set.addObjectsFromArray(ar)

我知道原因,那么如何将Array<Character>转换为[AnyObject]

1 个答案:

答案 0 :(得分:2)

字符不能转换为AnyObject。在将字符添加到计数集之前,您需要将字符映射到字符串:

let str = "Hello, playground"
let stringArray = str.characters.map{String($0)}
let countedSet = NSCountedSet()
countedSet.addObjectsFromArray(stringArray)