How to convert NSSet to [String] array?

前端 未结 4 1419
伪装坚强ぢ
伪装坚强ぢ 2021-02-09 07:00

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

相关标签:
4条回答
  • 2021-02-09 07:26
    let set = NSSet(array: ["a","b","c"])
    let arr = set.allObjects as! [String]
    
    0 讨论(0)
  • 2021-02-09 07:27

    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)
    
    0 讨论(0)
  • 2021-02-09 07:32

    You could do something like this.

    let set = //Whatever your set is
    var array: [String] = []
    
    for object in set {
         array.append(object as! String)
    }
    
    0 讨论(0)
  • 2021-02-09 07:33

    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
    

    0 讨论(0)
提交回复
热议问题