let myArray = Array(arrayLiteral: userIDs)
let newArray = myArray.map{$0 as! UInt}
What does the following error mean?
Cast from 'Set?' to unrelated type 'UInt' always fails
I want to convert an array created from NSSet to array with UInt instead of numbers.
If userIDs is Set<NSNumber> then doing Array(arrayLiteral: userIDs) does not create an array from the set contents, it creates an array containing the set itself.
Remove the arrayLiteral init:
let num1 = NSNumber(integer: 33)
let num2 = NSNumber(integer: 42)
let num3 = NSNumber(integer: 33)
let nums = [num1, num2, num3] // [33, 42, 33]
let userIDs = Set(nums) // {33, 42}
let myArray = Array(userIDs) // [33, 42]
Then you can map to whatever you want:
let newArray = myArray.map{ UInt($0) }
UPDATE after your comment
If you have a Foundation's NSSet instead of a Swift's Set, you can do this:
let userIDs = NSSet(array: nums)
let myArray = userIDs.map { $0 as! NSNumber }
let newArray = myArray.map { UInt($0) }
We have to downcast the content of NSSet to NSNumber since NSSet doesn't retain the element's type.
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