Set a variable to the < (“less than”) operator as a function in Swift?

后端 未结 1 700
执念已碎
执念已碎 2021-01-12 09:38

There\'s a neat guide here about overloading operators in Swift, but it doesn\'t say anything about treating operators as functions that I can pass around as variables like

相关标签:
1条回答
  • 2021-01-12 10:36

    If you give comparator an explicit type, then it will work.

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

    or

    var comparator: (Double, Double) -> Bool = (<)
    

    Less than < isn't a single function, but a whole collection of them for different types. By identifying the type you are interested in comparing, you allow the compiler to select the correct less than function.

    0 讨论(0)
提交回复
热议问题