是否可以使用三元 if 运算符进行模式匹配?
考虑以下示例:
let someString: String? = ...
if let embedURL = embedURL {
return NSURL(string: embedURL)
} else {
return nil
}
这是冗长的。我希望能够做这样的事情:
return let someString = someString ? NSURL(string: someString) : nil
或
return case let .Some(someString) = someString ? NSURL(string: someString) : nil
但是编译器不接受。我知道我可以向接受可选字符串的 NSURL
添加一个初始化器,使用普通的 if
语句甚至 switch
语句,但我想知道是否可以使用三元 if
运算符,或者在将来的某个时候是否可以。
最佳答案
不能在三元条件运算符的条件中使用模式匹配。
但是您可以改用可选的 flatMap()
方法:
/// Returns `nil` if `self` is nil, `f(self!)` otherwise.
public func flatMap<U>(@noescape f: (Wrapped) throws -> U?) rethrows -> U?
在你的情况下:
let someString: String? = ...
let url = someString.flatMap { NSURL(string: $0) }
表达式的类型是 NSURL?
,它的计算结果为 nil
如果 someString == nil
或者 NSURL(string:)
返回 nil
。
正如@Cosyn 所注意到的,最后一行也可以写成
let url = someString.flatMap(NSURL.init)
关于swift - 使用三元 if 运算符的模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33278240/