最近,我正在阅读“ 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改进