美文网首页
一块条件绑定语法糖

一块条件绑定语法糖

作者: WhiteWhite_iOS | 来源:发表于2016-06-18 19:30 被阅读11次

条件绑定

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.... }

相关文章

网友评论

      本文标题:一块条件绑定语法糖

      本文链接:https://www.haomeiwen.com/subject/hfcbdttx.html