Nav Brar
Nav Brar

Reputation: 384

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

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

Upvotes: -2

Views: 188

Answers (2)

Nav Brar
Nav Brar

Reputation: 384

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]

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236260

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

Upvotes: 1

Related Questions