More syntax for ternary with let?
Is there a better way to accomplish the DEF assignment in the following example? I want to convert type A to type B, but still retain the nil option when I can.
It doesn't look like he'll stumble in the best way to do it. Suggestions?
class ABC {
var DEF: Int?
func X (someValue: Int8?) {
DEF = someValue != nil ? Int(someValue) : nil
}
}
source to share
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, expands it, and applies a function to it. map()
Returns nil if the option allows nil.
source to share
You describe the 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 a map like an array or other collectible map where optionals are collections that have either a null ( nil
) or one (non nil
) item.
Note, if the operation you want to perform itself returns an optional parameter, you need flatMap
to avoid the 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?
source to share