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

标签 ios swift

我试图在不提供参数的情况下在类中声明一个结构。该结构将需要由函数初始化,但应该对整个类可见。通常,我可以执行 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/

相关文章:

ios - 无法在 Xcode 中查看配置文件

ios - 在 iOS 中给出方向

ios - 访问 token 过期后处理多个未经授权的请求

swift - swift 结构二叉树

ios - 符合 Equatable 的单元测试策略

ios - 选择单元格内的图表时,如何停用 tableView 单元格内的垂直滚动?

objective-c - UITableView reloadData 导致 UITextField resignFirstResponder

ios - 在 SDAnimatedImageView 中重复源图像

ios - 如何快速清除带有代码的标签的内容?

swift - 通过 transform.scale 属性动画化 CAShapeLayer 的路径