【问题标题】:Infix % operator works in Playground, but not in included Swift library中缀 % 运算符适用于 Playground,但不适用于包含的 Swift 库
【发布时间】:2021-06-23 18:15:12
【问题描述】:

我正在尝试为 Swift 中的双打重载 % 运算符。我意识到 Double 类型的两种方法存在的原因,但是 truncatingRemainder() 的行为对我的用例来说很好。

我正在使用 Xcode Playgrounds 来解决这个问题,我认为我已经解决了。

infix operator %

func % (left: Double, right: Double) -> Double {
    return left.truncatingRemainder(dividingBy: right)
}

var x = 0.0

for _ in 0...5 {
    print(x)
    x = (x + 1.5) % 5.0
}

print(x)

这很好用,并给了我正确的预期行为。

在此之后,我尝试将其放入我正在研究的库中。我创建了一个新的 .swift 文件,重建了库,确保导入语句在我的 Playground 中正常工作(通过使用库中的其他函数/方法),但出现以下错误:

  • 为运算符找到不明确的运算符声明
  • 无法将“()”类型的值转换为预期的参数类型“Double”
  • 运算符不是已知的二元运算符

谁能解释将其放入我的 Playground 和将其包含在导入文件中的区别?

【问题讨论】:

    标签: swift swift-playground xcplayground


    【解决方案1】:

    对于库,您只需声明具有公共访问权限的函数。不需要infix operator %。您正在执行运算符重载。

    public func % (left: Double, right: Double) -> Double {
        return left.truncatingRemainder(dividingBy: right)
    }
    

    在使用自定义运算符时需要infix operator。赞infix operator **

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 2021-04-23
      • 1970-01-01
      • 2012-05-21
      • 2018-11-22
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多