1

I want to optionally cast an NSNumber? to an Int?, but the initialiser method for Int only takes init(NSNumber), so I can't pass an NSNumber?.

Is there a way for me to compact this code so that it uses something like optional chaining?

// number: NSNumber?
let integer = number == nil ? nil : Int(number!)
vrwim
  • 13,020
  • 13
  • 63
  • 118

1 Answers1

4

The Int constructors don't take optional arguments. You could "wrap" the construction into map():

let number : NSNumber? = ...
let n = number.map { Int($0) } // `n` is an `Int?`

But here it is easier to use the integerValue property of NSNumber with optional chaining:

let n = number?.integerValue // `n` is an `Int?`

or just

let n = number as? Int // `n` is an `Int?`

since Swift "bridges" between NSNumber and Int automatically.

phatmann
  • 18,161
  • 7
  • 61
  • 51
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382