为 Swift 中的运算符转义闭包
Escaping closure for operators in Swift
如何将用于计算运算符的函数存储在 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 [=12=] <
}
请注意 <
实际上是 Swift 3 中 Comparable
上的静态函数,顶级运算符 <
只是它的包装器:
public protocol Comparable : Equatable {
...
public static func <(lhs: Self, rhs: Self) -> Bool
...
}
用括号括起来
let comparator: (Int, Int) -> Bool = (<)
如何将用于计算运算符的函数存储在 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 [=12=] <
}
请注意 <
实际上是 Swift 3 中 Comparable
上的静态函数,顶级运算符 <
只是它的包装器:
public protocol Comparable : Equatable {
...
public static func <(lhs: Self, rhs: Self) -> Bool
...
}
用括号括起来
let comparator: (Int, Int) -> Bool = (<)