我想将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]
?
答案 0 :(得分:2)
字符不能转换为AnyObject。在将字符添加到计数集之前,您需要将字符映射到字符串:
let str = "Hello, playground"
let stringArray = str.characters.map{String($0)}
let countedSet = NSCountedSet()
countedSet.addObjectsFromArray(stringArray)