【问题标题】:How can I define a postfix operator on a tuple?如何在元组上定义后缀运算符?
【发布时间】: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] } 将从StringInt 的字典中获取一个帧。
  • @Alexander 我刚刚使用了^^^ 使其非常清楚这不是存在冲突的现有运算符:P
  • 运算符对元组很好的主要原因是你不能扩展它们,所以添加方法是不可能的。 并且 你可以对元组做中缀操作符。我猜只是不是后缀?

标签: swift tuples custom-operator


【解决方案1】:

这是一个已知错误,比较 Swift 论坛中的 Prefix and postfix operators not working for tuple typesSR-294 Strange errors for unary prefix operator with tuple arg.

已针对 Swift 5 修复,以下在 Xcode 10.2 beta 4 中编译和运行:

postfix operator ^^^

public postfix func ^^^<T>(lhs: (T, T)) -> [T] {
    return [lhs.0, lhs.1]
}

let x = (0, 0)^^^
print(x) // [0, 0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-10
    • 1970-01-01
    相关资源
    最近更新 更多