简体   繁体   中英

Escaping closure for operators in Swift

How can I store the function used to evaluate an operator in a variable in Swift?

Neither Int.< nor Int.`<` seem to compile for me.

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:

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

放在方括号内

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM