类型 'Protocol' 的值没有成员 'Function'。

3
在下面的代码中,当我尝试访问genericVar.someFunc()时,我会得到错误信息:

"Value of type 'MyProtocol?' has no member 'someFunc'"。

作为一个泛型变量,当我初始化MyOtherStruct对象时,我必须传递一个符合MyProtocol协议的具体实现对象,那么为什么会出现这个错误呢?"最初的回答"
public protocol MyProtocol {

    associatedtype T
    func someFunc() -> T
}

public struct myStruct: MyProtocol {
    public typealias T = Int16

    public func someFunc() -> Int16 {
        let myVar: Int16 = 7
        return myVar
    }
}

public struct myOtherStruct<MyProtocol> {

    var genericVar: MyProtocol?

    public init(localVal: MyProtocol?) {
        self.genericVar = localVal
        if genericVar != nil {
            var my = genericVar.someFunc()
        }
    }
}
1个回答

3
您的普通类型声明有误。方括号中的MyProtocol是泛型类型参数的名称,而不是实际协议的名称。您需要为泛型类型参数声明另一个名称,并将其限制为MyProtocol,就像这样:struct MyOtherStruct<T:MyProtocol>。在这里,T将是结构体的泛型类型参数,而:MyProtocol语法强制要求T符合MyProtocol
public struct MyOtherStruct<T:MyProtocol> {
    var genericVar: T?

    public init(localVal: T?) {
        self.genericVar = localVal
        if let genericVar = genericVar {
            let my = genericVar.someFunc()
        }
    }
}

一些其他需要考虑的事情:你应该遵循Swift命名规则,即类型使用UpperCamelCase,当你要访问Optional值的属性/方法时,不要像if genericVar != nil那样进行nil比较,而是应该使用可选绑定if let


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接