HandyOperators

提供一些通用的操作符,以实现更简洁、更具表现力的代码。

<- ("with",“使用”)

将闭包应用于一个值,并返回转换后的副本。

final class Client {
    // with HandyOperators
    let jsonDecoder1 = JSONDecoder() <- {
        $0.dateDecodingStrategy = .iso8601
    }
    
    // without HandyOperators
    let jsonDecoder2: JSONDecoder = {
        let jsonDecoder = JSONDecoder()
        jsonDecoder.dateDecodingStrategy = .iso8601
        return jsonDecoder
    }()
}

也适用于轻松地将变异函数应用于副本。

extension Array {
    // with HandyOperators
    func appending1(_ element: Element) -> Self {
        self <- { $0.append(element) }
    }
    
    // without HandyOperators
    func appending2(_ element: Element) -> Self {
        var copy = self
        copy.append(element)
        return copy
    }
}

??? (unwrap or throw,“解包或抛出”)

接受一个可选值和一个错误(自动闭包,所以是惰性的),并返回解包后的可选值;如果可选值为 nil,则抛出错误。

// with HandyOperators
func doSomething1(with optional: String?) throws {
    print(try optional ??? MissingValueError())
}

// without HandyOperators
func doSomething2(with optional: String?) throws {
    guard let value = optional else { throw MissingValueError() }
    print(value)
}