【问题标题】:swift inconsistent generic protocol restrictionswift不一致的通用协议限制
【发布时间】:2016-09-23 06:52:49
【问题描述】:

在将参数传递给具有协议限制的通用函数时,我似乎遇到了编译器不一致的问题。我可以传递一个具体的参数,但不能将参数作为协议类型传递

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 协议,它仍然会失败。

这是编译器错误吗?有什么想法吗?

【问题讨论】:

    标签: swift generics protocols restriction


    【解决方案1】:

    如果您使用的是协议,则不需要是通用的:

    func myfunc(arg: Selectable) {
        arg.select()
    }
    

    我认为T 需要是泛型的具体类型。

    【讨论】:

    • 啊,非常正确,这让我解决了这个问题。是的,据我通过其他示例可以看出,泛型类型必须是具体的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多