【发布时间】:2015-12-03 10:11:02
【问题描述】:
这是我的代码:
protocol Logable {
func log()
}
extension Logable where Self: Error {
func log() {
switch self {
case .Server(code: Int, message: String):
print("code = \(code), message = \(message)")
}
}
}
enum Error: Logable {
case Client(code: Int, message: String)
case Server(code: Int, message: String)
}
如您所见,我想为我的枚举 Error 创建协议 LogableError 的默认实现。也许不可能 - 请提供链接。不要在操场上运行它,它不会显示任何内容,但编译器会给出错误:
type 'Self' constrained to non-protocol type 'Error'
【问题讨论】:
-
在协议扩展中尝试
Self == Error -
@Roshan 它给了
Same-type requirement makes generic parameter 'Self' non-generic -
是的,有点预感它不会工作...如果您需要为特定类型实现协议,您将在类型本身而不是协议上添加扩展...
-
请注意,“默认实现”对于枚举没有多大意义,因为无论如何您都不能从它们继承。我怀疑如果您将枚举替换为严格的(例如,Int),上述解决方案可能会起作用......
标签: swift enums swift2 protocols