vrwim vrwim - 3 months ago 16
Swift Question

Optional chaining for constructor calls?

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!)

Answer

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.

Comments