Swift4 自定义操作符

整理自 Swift4进阶

可选值操作

infix operator ???: NilCoalescingPrecedence
/// ??? 操作符
/// 在字符串插值中使用可选值
/// 这个函数接受左侧的可选值 T? 和右侧的字符串。如果可选值不是nil,我们将它解包,然后返回它的字符串描述。
/// 否则,我们将传入的默认字符串返回
///
///     eg:
///     let bodyTemperature: Double? = 37.0
///     let bloodGlucose: Double? = nil
///     print("Body temperature: \(bodyTemperature ??? "n/a")")
///     //Body temperature: 37.0
///     print("Blood glucose level: \(bloodGlucose ??? "n/a")")
///     // Blood glucose level: n/a
///
/// - Parameters:
///   - optional: 可选值
///   - defaultValue: 默认值(字符串)
/// - Returns: 字符串
func ???(optional: T?, defaultValue: @autoclosure() -> String) -> String {
    switch optional {
    case let value?: return String(describing: value)
    case nil: return defaultValue()
    }
}

infix operator !!
/// !! 操作符
/// 强制解包失败时输入错误信息
///
///     eg:
///     let s = "foo"
///     let i = Int(s) !! "Expecting integer, got\"\(s)\""
///     // will print fatal error: Expecting integer, got"foo"
///
/// - Parameters:
///   - wrapped: 可选值
///   - failureText: 错误信息
/// - Returns: 被解包值
func !!(wrapped: T?, failureText: @autoclosure () -> String) -> T {
    if let x = wrapped { return x }
    fatalError(failureText())
}

infix operator !?
/// !? 操作符
/// 在调试版本中进行断言
///
///     eg:
///     let s = "2a"
///     let i = Int(s) !? (5, "Expected Integer")
///     // 调试版本中会触发断言 Expected Integer
///     // 发布版本中 i = 5
///
/// 对失败的解包进行断言,并且在断言不触发的发布版本中将值替换为默认值
/// - Parameters:
///   - wrapped: 可选值
///   - nilDefault: 解包失败断言操作
/// - Returns: 解包成功的值或者解包失败的默认值
func !?(wrapped: T?, nilDefault:@autoclosure () -> (value: T, text: String)) -> T {
    assert(wrapped != nil, nilDefault().text)
    return wrapped ?? nilDefault().value
}

/// !? 操作符
/// 对于返回 Void 的函数,使用可选链进行调用时将返回 Void?
/// 通过 !? 操作符来检测一个可选链调用碰到 nil,且没有进行操作的情况
///
///     eg:
///     var output: String? = nil
///     output?.write("some thing") !? "Wasn't expecting chained nil here"
///     //assertion failed: Wasn't expecting chained nil here
///
/// - Parameters:
///   - wrapped:
///   - failureText: 为nil且没有进行操作时的提示
func !?(wrapped: ()?, failureText: @autoclosure () -> String) {
    assert(wrapped != nil, failureText)
}

你可能感兴趣的:(Swift4 自定义操作符)