如何在Swift中自定义三元运算符 [英] How to customize ternary operators in Swift

查看:104
本文介绍了如何在Swift中自定义三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何自定义二元运算符,例如

I know how to customize binary operators, like this

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

但是,如何在Swift中定制三元运算符?谁能给我一些想法?非常感谢!

But, how to customize ternary operators in Swift? Can anyone give me some idea? Thanks so much!

推荐答案

可以通过声明两个独立的运算符来实现这一点,为其中一个操作员使用curried函数。

You can actually do this by declaring two separate operators that work together and using a curried function for one of the operators.

让我们声明一个三元运算符 x + - y + | - z 将检查初始值的符号 x ,然后返回第二个值 y 如果符号为零或正数且最终值 z 如果标志是否定的。也就是说,我们应该可以写:

Let's declare a ternary operator x +- y +|- z that will check the sign of the initial value x, and then return the second value y if the sign is zero or positive and the final value z if the sign is negative. That is, we should be able to write:

let sign = -5 +- "non-negative" +|- "negative"
// sign is now "negative"

我们首先宣布两个运营商。重要的是在第二个运算符上有更高的优先级 - 我们将首先评估该部分并返回一个函数:

We'll start by declaring the two operators. The important part is to have higher precedence on the second operator - we'll evaluate that part first and return a function:

infix operator +- { precedence 60 }
infix operator +|- { precedence 70 }

然后定义函数 - 我们将首先定义第二个:

Then define the functions - we'll define the second first:

func +|-<T>(lhs: @autoclosure () -> T, rhs: @autoclosure () -> T)(left: Bool) -> T {
    return left ? lhs() : rhs()
}

这里的重要部分是这个函数是curried - 如果你只用前两个参数调用它,而不是返回一个 T 值,它返回一个(左:Bool) - > ; T 功能。这成为我们第一个运算符函数的第二个参数:

The important part here is that this function is curried -- if you only call it with the first two parameters, instead of returning a T value, it returns a (left: Bool) -> T function. That becomes the second parameter of the function for our first operator:

func +-<I: SignedIntegerType, T>(lhs: I, rhs: (left: Bool) -> T) -> T {
    return rhs(left: lhs >= 0)
}

现在我们可以使用我们的三元运算符,如下所示:

And now we can use our "ternary" operator, like this:

for i in -1...1 {
    let sign = i +- "" +|- "-"
    println("\(i): '\(sign)'")
}
// -1: '-'
// 0: ''
// 1: ''






注意:我写了关于这个主题的博客文章与另一个例子。


Note: I wrote a blog post on this subject with another example.

这篇关于如何在Swift中自定义三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆