How to customize ternary operators in Swift

前端 未结 3 631
梦如初夏
梦如初夏 2020-12-16 01:30

I know how to customize binary operators, like this

infix operator ** { associativity left precedence 170 }
func ** (left: Double, right: Double) -> Doubl         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-16 02:23

    A "true" ternary operator such as _ ? _ : _ requires language support. Swift allows creating and customizing only unary and binary operators.

    You can use the technique in @NateCook's answer to make a pair of binary operators which together work like a ternary operator, but they're still independent binary operators -- you can use either on its own. (By contrast, _ ? _ : _ is only a ternary operator; _ ? _ and _ : _ can't be used individually.)

    Of course, why stop there? You could chain more binary operators to create quaternary operators, and so on. For extra credit, try making yourself an extended spaceship operator:

    let c: String = a <=> b
        |<| "a < b"
        |=| "a = b"
        |>| "a > b"
    

    (...but please do this as an academic exercise only, or anyone else who works with code you write will hate you.)

提交回复
热议问题