Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using pattern matching with ternary if operator

Tags:

swift

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.

like image 940
Andrii Chernenko Avatar asked Mar 14 '23 09:03

Andrii Chernenko


2 Answers

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)
like image 181
Martin R Avatar answered Apr 01 '23 00:04

Martin R


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.

like image 29
Steve Wilford Avatar answered Mar 31 '23 23:03

Steve Wilford