Distribute an option through a function (or Init) in Swift

Does anyone have a (best) way to do this?

Let's say I have an optional Float

let f: Float? = 2

Now I want to transfer it to Double

let d = Double(f) //fail

This obviously will not succeed, but is there a way to associate the optional through the function, as you can, with the calculated variables? Now I do the following:

extension Float {
    var double: Double { return Double(self) }
}
let d: Double? = f?.double

But I really don't like to set the translation as a computed variable.

Another option I considered is the following:

public func optionalize<A,B>(_ λ : @escaping (A) -> B) -> (A?) -> B? {
    return { (a) in
        guard let a = a else { return nil }
        return λ(a)
    }
}
let d: Double? = optionalize(Double.init)(f)

I understand that I can protect the value of "f" to expand it. However, in many cases, an optional value will be a parameter for a function that returns an optional parameter. This leads to intermediate values ​​in the guard. As seen in this example:

func foo(_ a: String?) throws -> Float {
    guard 
        let a = a,
        let intermediate = Float(a)
    else { throw.something }
    return intermediate
}

String to Float. , foo

extension String {
    var float: Float? { return Float(self) }
}

func foo(_ a: String?) throws -> Float {
    guard 
        let a = a?.float
    else { throw.something }
    return a
}

inits.

. !

+4
1

Optional map(_:), , nil, 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) }

, , :

let d = f.map(Double.init)

, map(_:) (Float) -> Double, Double float .

(, String Int), flatMap(_:), nil :

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) }
+4

Source: https://habr.com/ru/post/1658261/


All Articles