【问题标题】:binary operator cannot be applied to operands二元运算符不能应用于操作数
【发布时间】:2016-02-18 21:06:35
【问题描述】:

最近,我正在阅读“swift 中的函数式编程”。在书中,作者对 Int 做了一些扩展以满足协议Smaller。为了深入理解作者的思路,我把代码复制到自己的playground,但是报错。

protocol Smaller {
    static func smaller() -> Self?
}

extension Int: Smaller {
    static func smaller() -> Int? {
      //reporting error: Binary operator "==" cann't be applied to type of Int.type and Int  
      return self == 0 ? nil : self / 2
    }
}

似乎self == 0 在扩展中是不允许的。有没有人知道原因。

【问题讨论】:

  • 我不知道swift,但是为什么协议和扩展(返回类型)中方法的签名不同?
  • 这是 swift 协议的规则,必须将 Self 替换为类型本身。
  • static 方法中,关键字self 指的是类型,而不是实际实例,因此您不应使用static,因为它看起来像是您想要使用的Int 的实例
  • 哦,是的,我认为你是对的。非常感谢。
  • 你能给你的评论一个答案吗,我会采纳的。@DánielNagy

标签: swift2


【解决方案1】:

我认为您不想使用静态函数,因为您需要一个实例化的整数来处理并检查它是否更小。

所以有两种方法:

  • 从函数中去掉静态,然后正常调用: let aInt = 4 aInt.smaller() //will be 2

  • 或者您更改静态函数的签名以接受实例作为参数

`

protocol Smaller {
  static func smaller(selfToMakeSmall: Self) -> Self?
}

extension Int: Smaller {
  static func smaller(selfToMakeSmall: Int) -> Int? {
    //reporting error: Binary operator "==" cann't be applied to type of Int.type and Int
    return selfToMakeSmall == 0 ? nil : selfToMakeSmall / 2
  }
}


let theInt = 4
Int.smaller(theInt)

`

但我认为这也可以通过泛型来改进

【讨论】:

    猜你喜欢
    • 2016-04-10
    • 2016-08-17
    • 2015-09-01
    • 2018-01-18
    • 2017-11-22
    • 2018-06-23
    • 2023-03-10
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多