4

Is there a nicer way to do the assignment to DEF in the following example? I want to convert type A to Type B, but still preserve the nil possibility whenever I can.

Can't seem to stumble into a better way of doing this, however. Suggestions?

class ABC {

  var DEF: Int?

  func X (someValue: Int8?) {
    DEF = someValue != nil ? Int(someValue) : nil
  }
}
MarcWan
  • 2,943
  • 3
  • 28
  • 41
  • 1
    you might find [this list of ways to handle optionals](http://stackoverflow.com/questions/29717210/when-should-i-compare-an-optional-value-to-nil/29717211#29717211) useful – Airspeed Velocity Jul 06 '15 at 13:34

2 Answers2

2

Swift 1:

class ABC {

  var DEF: Int?

  func X (someValue: Int8?) {
    DEF = someValue.map{Int($0)}
  }
}

Swift 2:

class ABC {

  var DEF: Int?

  func X (someValue: Int8?) {
    DEF = someValue.map(Int.init)
  }
}

map() takes an optional, unwraps it, and applies a function to it. If the optional resolves to nil, map() returns nil.

oisdk
  • 9,763
  • 4
  • 18
  • 36
1

You are describing optional map:

var i: Int? = 2
let j = i.map { $0 * 2 }  // j = .Some(4)
i = nil
let k = i.map { $0 * 2 }  // k = nil

Think of this map like array or other collection map, where optionals are collections that have either zero (nil) or one (non-nil) element.

Note, if the operation you want to perform itself returns an optional, you need flatMap to avoid getting a double-optional:

let s: String? = "2"
let i = s.map { Int($0) }      // i will be an Int??
let j = s.flatMap { Int($0) }  // flattens to Int? 
Airspeed Velocity
  • 40,491
  • 8
  • 113
  • 118