我有一个NSSet of Strings,我想把它转换为[String]。我该怎么做?
答案 0 :(得分:12)
我会使用map
:
let nss = NSSet(array: ["a", "b", "a", "c"])
let arr = nss.map({ String($0) }) // Swift 2
let arr = map(nss, { "\($0)" }) // Swift 1
答案 1 :(得分:4)
如果您有Set<String>
,则可以使用Array构造函数:
let set: Set<String> = // ...
let strings = Array(set)
或者如果你有NSSet,有几个不同的选择:
let set: NSSet = // ...
let strings1 = set.allObjects as? [String] // or as!
let strings2 = Array(set as! Set<String>)
let strings3 = (set as? Set<String>).map(Array.init)
答案 2 :(得分:2)
let set = NSSet(array: ["a","b","c"])
let arr = set.allObjects as! [String]
答案 3 :(得分:1)
你可以这样做。
let set = //Whatever your set is
var array: [String] = []
for object in set {
array.append(object as! String)
}