gpt4 book ai didi

swift - 类型 'Protocol' 的值没有成员 'Function'

转载 作者:行者123 更新时间:2023-11-30 10:38:09 25 4
gpt4 key购买 nike

在下面的代码中,当我尝试访问 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()
}
}
}

最佳答案

您的泛型类型声明是错误的。 MyProtocol括号中是泛型类型参数的名称,而不是实际的协议(protocol)。您需要为泛型类型参数声明另一个名称并将其限制为 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 命名约定,即类型的大驼峰式命名约定,并且当您想要访问可选值的属性/方法时,而不是执行 nil比较如 if genericVar != nil您应该使用 if let 来使用可选绑定(bind).

关于swift - 类型 'Protocol' 的值没有成员 'Function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57449995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com