【发布时间】: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
}
请注意,< 实际上是 Swift 3 中 Comparable 上的静态函数,而顶级运算符 < 只是它的包装器:
public protocol Comparable : Equatable {
...
public static func <(lhs: Self, rhs: Self) -> Bool
...
}
【问题讨论】:
标签: swift generics operator-overloading operators currying