我正在阅读 advanced operators swift 。
基本功能:
func add(a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
add(u1, u2) // two unicorns are added
中缀运算符:
func + (a: Unicorn, b: Unicorn) -> Unicorn { return a + b }
c = u1 + u2
后缀:
postfix func + (a: Unicorn) -> Unicorn { return a + 2 } // nonsense example
u1+
我不明白如何将 infix
假定为默认值。在我看来,它与普通函数声明没有任何不同。
这里的规则是什么——任何单个字符都是中缀操作的合法名称吗?这是否意味着不允许使用单个 char 函数? 任何 swift 中的双参数函数都可以称为中缀样式吗?
最佳答案
I don't understand how infix can be presumed to be the default.
如果您使用两个参数实现运算符,编译器可以确定您需要一个中缀运算符,因为只有中缀运算符对两个值进行运算。
如果您使用一个值实现一个运算符,编译器不确定它是前缀运算符还是后缀运算符,并且会报错。
中缀运算符有两个值,后缀和前缀只有一个。
Does this mean single char functions are not otherwise allowed? Can any two-argument function in swift be called infix style?
没有。以以下任何字符开头的函数都是运算符:/、=、-、+、!、*、%、<、>、&、|、^、? 或 ~1。一个运算符也可以由多个字符组成,但它必须以这些字符之一开头。
请记住,必须先声明一个新的运算符,例如:
prefix operator / {}
prefix func / (a: Int) -> Int {
return a / 42
}
/56
但是这个声明不起作用,因为 a
不是运算符必须开始的字符之一:
prefix operator a {}
1 其实还有更多的字符。阅读here .
关于swift - 为什么默认是 `infix`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555979/