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