How to convert NSSet to [String] array?

青春壹個敷衍的年華 提交于 2021-02-17 22:54:03

问题


I have an NSSet of Strings, and I want to convert it into [String]. How do I do that?


回答1:


I would use map:

let nss = NSSet(array: ["a", "b", "a", "c"])

let arr = nss.map({ String($0) })  // Swift 2

let arr = map(nss, { "\($0)" })  // Swift 1




回答2:


If you have a Set<String>, you can use the Array constructor:

let set: Set<String> = // ...
let strings = Array(set)

Or if you have NSSet, there are a few different options:

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)



回答3:


let set = NSSet(array: ["a","b","c"])
let arr = set.allObjects as! [String]



回答4:


You could do something like this.

let set = //Whatever your set is
var array: [String] = []

for object in set {
     array.append(object as! String)
}


来源:https://stackoverflow.com/questions/31662297/how-to-convert-nsset-to-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!