How can I convert an array of NSNumbers to an array of Ints?

90 views Asked by At

How to get Int value from NSNumber in Swift? Or convert array of NSNumber to Array of Int values?

I have a list of NSNumber

let array1:[NSNumber] 

I want a list of Int values from this array

let array2:[Int] = Convert array1
2

There are 2 answers

1
Leo Dabus On

It depends what is the expected result if there is non integer elements in your collection.

let array1: [NSNumber] = [1, 2.5, 3]

If you want to keep the collection only if all elements are integers

let array2 = array1 as? [Int] ?? []           //  [] all or nothing

If you want to get only the integers from the collection

let array3 = array1.compactMap { $0 as? Int } //  [1, 3] only integers

If you want the whole value of all elements

let array4 = array1.map(\.intValue)           //  [1, 2, 3] whole values
0
Nav Brar On

I have fixed this issue with one line of code:

  let array1 : [NSNumber] = [1, 2.5, 3]

  let array2 =  array1.compactMap {Int(truncating: $0)}

  let array3 =  array1.compactMap(Int.init)

it returns an array of Int values.

Result of array2 = [1,2,3]
Result of array3 = [1,3]