【发布时间】:2019-03-22 17:39:30
【问题描述】:
我有以下代码:
postfix operator ^^^
public postfix func ^^^(lhs: Int) -> Int {
return 0
}
public postfix func ^^^<T>(lhs: (T, T)) -> [T] {
return [lhs.0, lhs.1]
}
func go() {
1^^^ // this works
(0, 0)^^^ // error: Unary operator '^^^' cannot be applied to an operand of type '(Int, Int)'
}
我得到了错误,Unary operator '^^^' cannot be applied to an operand of type '(Int, Int)'。任何想法如何解决这个问题?
【问题讨论】:
-
是的,我明白你的意思了!看起来后缀运算符不适用于元组。真的不是很令人惊讶。也许您可以在实际用例中改用结构。元组确实是一种不合标准的类型,并且有很多事情它们不做(例如,元组相等也一直是一个主要问题)。
-
从未想过在元组上定义运算符。虽然如果我在代码库中看到
(0, 0)^^^,头部会滚动:p -
元组作为序列有一些非常好的用途,例如:
(x, y, width, height) = ("x", "y", "width", "height")^^^.map { dict[$0] }将从String到Int的字典中获取一个帧。 -
@Alexander 我刚刚使用了
^^^使其非常清楚这不是存在冲突的现有运算符:P -
运算符对元组很好的主要原因是你不能扩展它们,所以添加方法是不可能的。 并且 你可以对元组做中缀操作符。我猜只是不是后缀?
标签: swift tuples custom-operator