[英]Escaping closure for operators in Swift
How can I store the function used to evaluate an operator in a variable in Swift? 如何在Swift的变量中存储用于求值运算符的函数?
Neither Int.<
nor Int.`<`
seem to compile for me. Int.<
和Int.`<`
似乎都没有为我编译。
For alphanumeric function names, this works just fine: 对于字母数字函数名称,这可以正常工作:
extension Comparable {
static func lessThan(_ lhs: Self, _ rhs: Self) -> Bool {
return lhs < rhs
}
}
let comparator = Int.lessThan
I know I can create a new closure like this, but I feel like there must be a more elegant way: 我知道我可以像这样创建一个新的闭包,但是我觉得必须有一个更优雅的方法:
let comparator: (Int, Int) -> Bool = {
return $0 < $1
}
Please note that <
actually is a static function on Comparable
in Swift 3, and the top-level operator <
only is a wrapper for that: 请注意, <
实际上是Swift 3中Comparable
上的静态函数,而顶级运算符<
仅是该封装器:
public protocol Comparable : Equatable {
...
public static func <(lhs: Self, rhs: Self) -> Bool
...
}
放在方括号内
let comparator: (Int, Int) -> Bool = (<)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.