Propagate an optional through a function (or Init) in Swift

后端 未结 1 709
死守一世寂寞
死守一世寂寞 2020-12-02 00:47

does anyone have a (better) way to do this?

Lets say I have a optional Float

let f: Float? = 2

Now I want to cast it to a Double

相关标签:
1条回答
  • 2020-12-02 01:14

    You can simply use Optional's map(_:) method, which will return the wrapped value with a given transform applied if it's non-nil, else it will return nil.

    let f : Float? = 2
    
    // If f is non-nil, return the result from the wrapped value passed to Double(_:),
    // else return nil.
    let d = f.map { Double($0) }
    

    Which, as you point out in the comments below, can also be said as:

    let d = f.map(Double.init)
    

    This is because map(_:) expects a transformation function of type (Float) -> Double in this case, and Double's float initialiser is such a function.

    If the transform also returns an optional (such as when converting an String to a Int), you can use flatMap(_:), which simply propagates a nil transform result back to the caller:

    let s : String? = "3"
    
    // If s is non-nil, return the result from the wrapped value being passed to the Int(_:)
    // initialiser. If s is nil, or Int($0) returns nil, return nil.
    let i = s.flatMap { Int($0) }
    
    0 讨论(0)
提交回复
热议问题