swift 不一致的通用协议限制
swift inconsistent generic protocol restriction
在将参数传递给具有协议限制的通用函数时,我似乎 运行 遇到编译器不一致的问题。我可以传递一个具体的参数,但不能传递一个作为协议类型的参数
protocol Selectable {
func select()
}
protocol Log : Selectable {
func write()
}
class DefaultLog : Log {
func select() {
print("selecting")
}
func write() {
print("writing")
}
}
let concrete = DefaultLog()
let proto: Log = DefaultLog()
func myfunc<T: Selectable>(arg: T) {
arg.select()
}
myfunc(concrete) // <-- This works
myfunc(proto) // <-- This causes a compiler error
proto.write() // <-- This works fine
编译器报告:
error: cannot invoke 'myfunc' with an argument list of type '(Log)'
myfunc(proto)
^
note: expected an argument list of type '(T)'
myfunc(proto)
^
如果我将函数限制为 Selectable 或 Log 协议,它仍然会失败。
这是编译器错误吗?有什么想法吗?
如果您使用的是协议,则它不需要是通用的:
func myfunc(arg: Selectable) {
arg.select()
}
我相信 T
需要成为泛型的具体类型。
在将参数传递给具有协议限制的通用函数时,我似乎 运行 遇到编译器不一致的问题。我可以传递一个具体的参数,但不能传递一个作为协议类型的参数
protocol Selectable {
func select()
}
protocol Log : Selectable {
func write()
}
class DefaultLog : Log {
func select() {
print("selecting")
}
func write() {
print("writing")
}
}
let concrete = DefaultLog()
let proto: Log = DefaultLog()
func myfunc<T: Selectable>(arg: T) {
arg.select()
}
myfunc(concrete) // <-- This works
myfunc(proto) // <-- This causes a compiler error
proto.write() // <-- This works fine
编译器报告:
error: cannot invoke 'myfunc' with an argument list of type '(Log)'
myfunc(proto)
^
note: expected an argument list of type '(T)'
myfunc(proto)
^
如果我将函数限制为 Selectable 或 Log 协议,它仍然会失败。
这是编译器错误吗?有什么想法吗?
如果您使用的是协议,则它不需要是通用的:
func myfunc(arg: Selectable) {
arg.select()
}
我相信 T
需要成为泛型的具体类型。