条件绑定
if let value = targetValue {
//targetValue == nil
}else {
//targetValue = nil
}
快捷写法
//声明
infix operator ??? {associativity left precedence 101}
func ???<T>(targetValue: T?, @autoclosure defaultValue: () throws -> T) rethrows -> T {
if let value = targetValue {
return x
}else {
return try defaultValue()
}
}
//快捷写法
let value = targetValue ??? ( defaultValue )
Reference: Functional Swift (objc.io)
!!!自己打脸:这种写法是冗余的,optional自带map方法!!!**
public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
......
/// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`.
@warn_unused_result
public func map<U>(@noescape f: (Wrapped) throws -> U) rethrows -> U?
......
}
//用法
let value = targetValue.map{ $0.... }