Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: NSArray to Set?

Tags:

swift

set

nsarray

I am trying to convert an NSArray to a Swift Set.

Not having much luck.

What is the proper way to do so?

For example if I have an NSArray of numbers:

@[1,2,3,4,5,6,7,8]

How do I create a Swift Set from that NSArray?

like image 494
zumzum Avatar asked Dec 03 '22 15:12

zumzum


1 Answers

If you know for sure that the NSArray contains only number objects then you can convert it to an Swift array of Int (or Double or NSNumber, depending on your needs) and create a set from that:

let nsArray = NSArray(array: [1,2,3,4,5,6,7,8])
let set = Set(nsArray as! [Int])

If that is not guaranteed, use an optional cast:

if let set = (nsArray as? [Int]).map(Set.init) {
    print(set)
} else {
    // not an array of numbers
}

Another variant (motivated by @JAL's comments):

let set = Set(nsArray.flatMap { $0 as? Int })
// Swift 4.1 and later:
let set = Set(nsArray.compactMap { $0 as? Int })

This gives a set of all NSArray elements which are convertible to Int, and silently ignores all other elements.

like image 141
Martin R Avatar answered Jan 06 '23 02:01

Martin R