加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift2 – 二元运算符不能应用于操作数

发布时间:2020-12-14 04:30:53 所属栏目:百科 来源:网络整理
导读:最近,我正在阅读“ swift中的函数式编程”.在书中,作者对Int进行了一些扩展,以满足较小的协议.为了彻底了解作者的想法,我将代码复制到我自己的游乐场,但它报告错误. protocol Smaller { static func smaller() - Self?}extension Int: Smaller { static func
最近,我正在阅读“ swift中的函数式编程”.在书中,作者对Int进行了一些扩展,以满足较小的协议.为了彻底了解作者的想法,我将代码复制到我自己的游乐场,但它报告错误.

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
    }
}

似乎扩展中不允许自我== 0.有没有人知道原因.

解决方法

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

所以有两种方法:

>从函数中删除静态,然后正常调用它:

让aInt = 4
aInt.smaller()//将是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)

`

但我认为这也可以通过Generics改进

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读