How to customize ternary operators in Swift

前端 未结 3 626
梦如初夏
梦如初夏 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:31

    Here is how you can do it in Swift 4:

    precedencegroup SecondaryTernaryPrecedence {
        associativity: right
        higherThan: TernaryPrecedence
        lowerThan: LogicalDisjunctionPrecedence
    }
    
    infix operator ~ : SecondaryTernaryPrecedence
    
    func ~ (lhs: @autoclosure () -> Bool, rhs: @escaping @autoclosure () -> T) -> (Bool, () -> T) {
        return (lhs(), rhs)
    }
    
    infix operator >< : TernaryPrecedence
    
    @discardableResult func >< (lhs: (Bool, () -> T), rhs: @escaping @autoclosure () -> T) -> T {
        if lhs.0 {
            return lhs.1()
        } else {
            return rhs()
        }
    }
    

    Usage

    let n = false ~ "it was true" >< "it was false" //"it was false"
    
    true ~ print("it was true") >< print("it was false")
    // Prints "it was true"
    

    Note: While this is not a true ternary operator per se, as it uses two infix operators in conjunction with one another, it does in fact somewhat emulate its behaviour when the two operators are used together in the fashion presented above.

提交回复
热议问题