【发布时间】: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