最近,我正在阅读“
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改进
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。