-2

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
Ken White
  • 123,280
  • 14
  • 225
  • 444
Nav Brar
  • 202
  • 1
  • 9

2 Answers2

1

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
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    Thanks Leo, I was expecting to get 1 and 3 and I got it fixed with let array2 = array1.compactMap(Int.init) – Nav Brar Jun 01 '23 at 05:04
0

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]
Nav Brar
  • 202
  • 1
  • 9