Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift array.map conver NSNumber to UInt

Tags:

swift

swift2

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.

like image 722
Matrosov Oleksandr Avatar asked Aug 23 '26 08:08

Matrosov Oleksandr


1 Answers

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.

like image 132
Eric Aya Avatar answered Aug 26 '26 03:08

Eric Aya