gpt4 book ai didi

ios - 在 Swift 中初始化结构错误 : Generic parameter could not be inferred

转载 作者:可可西里 更新时间:2023-11-01 00:56:42 25 4
gpt4 key购买 nike

我试图在不提供参数的情况下在类中声明一个结构。该结构将需要由函数初始化,但应该对整个类可见。通常,我可以执行 var myStruct : MyStruct? 但这次它给我一个错误。

无法推断通用参数“Type”

我是否错误地初始化了结构?

我是如何使用它的:

class MyClass: {

static let sharedInstance = MyClass()
private override init() {}

let myStruct = MyStruct? // <-- Above Error occurs here.
// let myStruct = MyStruct<Int>? // <-- Error: Expected member name or constructor call after type name
// let myStruct = MyStruct<Int>?() // <-- Error: Cannot invoke initializer for type 'MyStruct<Double>?' with no arguments

func runFunction(A: Int, B: Int) {
myStruct(var1: A, var2: B) // <-- I need to initialize here.
}
func otherFunction() {
myStruct.doStuff() // <-- And have access to it in other functions
}

我的结构代码:

public struct MyStruct<Type: CustomInput>: CustomProtocol {
public let myVar1: Type
public let myVar2: Type
public init(var1: Type, var2: Type) {
self.myVar1 = var1
self.myVar2 = var2
}

...
}

最佳答案

对于泛型类型,泛型参数实际上被认为是类型的一部分。所以你的结构类型不是 MyStruct ,它是 MyStruct<Int> (或您使用的任何泛型类型。因此,如果编译器没有任何信息可用于推断实际类型,则不能仅自行声明类型。相反,您必须在声明中包含泛型类型:

var myStruct: MyStruct<Int>?

关于ios - 在 Swift 中初始化结构错误 : Generic parameter could not be inferred,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682585/

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