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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With