【问题标题】:Escaping closure for operators in SwiftSwift 中运算符的转义闭包
【发布时间】:2017-02-09 01:16:26
【问题描述】:

如何将用于评估运算符的函数存储在 Swift 中的变量中?

Int.<Int.`<` 似乎都不适合我。

对于字母数字函数名称,这很好用:

extension Comparable {
    static func lessThan(_ lhs: Self, _ rhs: Self) -> Bool {
        return lhs < rhs
    }
}

let comparator = Int.lessThan

我知道我可以像这样创建一个新的闭包,但我觉得必须有一个更优雅的方式:

let comparator: (Int, Int) -> Bool = {
    return $0 < $1
}

请注意,&lt; 实际上是 Swift 3 中 Comparable 上的静态函数,而顶级运算符 &lt; 只是它的包装器:

public protocol Comparable : Equatable {
    ...
    public static func <(lhs: Self, rhs: Self) -> Bool
    ...
}

【问题讨论】:

    标签: swift generics operator-overloading operators currying


    【解决方案1】:

    用括号括起来

    let comparator: (Int, Int) -> Bool = (<)
    

    【讨论】:

    • @ChristianSchnorr 不要 :) 这一点也不明显
    • 你知道是否也有办法将它作为类型的属性来访问?我猜(&lt;) 指的是顶级包装函数,不是Int 上的实际静态方法。
    • @ChristianSchnorr Int 上的哪个静态方法?
    • 小于符号&lt;,定义为Comparable中的要求。
    • @ChristianSchnorr “全局”&lt; 运算符满足一致性。 Int 上没有 static func 可以做到这一点。
    猜你喜欢
    • 2017-01-23
    • 1970-01-01
    • 2015-06-07
    • 2021-12-20
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多