Is it possible to use pattern matching with ternary if operator?
Consider the following examples:
let someString: String? = ...
if let embedURL = embedURL {
return NSURL(string: embedURL)
} else {
return nil
}
This is verbose. I would like to be able to do something like this:
return let someString = someString ? NSURL(string: someString) : nil
or
return case let .Some(someString) = someString ? NSURL(string: someString) : nil
But the compiler does not accept that. I know that I could add an initializer to NSURL
which accepts optional string, use normal if
statement or even switch
statement, but I would like to know if it is possible to do with the ternary if
operator, or whether it will be possible at some point in the future.
You cannot use pattern matching in the condition of the ternary conditional operator.
But you can use the flatMap()
method of optionals instead:
/// Returns `nil` if `self` is nil, `f(self!)` otherwise.
public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
In your case:
let someString: String? = ...
let url = someString.flatMap { NSURL(string: $0) }
The type of the expression is NSURL?
, and it evaluates to nil
if someString == nil
or if NSURL(string:)
returned nil
.
As @Cosyn noticed, the last line can also be written as
let url = someString.flatMap(NSURL.init)
You don't need to use pattern matching to achieve this.
return someString != nil ? NSURL(string: someString!) : nil
Is as close as you can get using the ternary operator as far as I can tell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With