简体   繁体   English

无法推断通用参数“T”,通用错误

[英]Generic parameter 'T' could not be inferred, Generic Error

I want to create a function to choose which implementation is good, like that:我想创建一个 function 来选择哪个实现好,像这样:

// As a BaseProtocol
protocol BaseProtocol {
    
}

// SeniorProtocol with associatedtype
protocol SeniorProtocol {
    associatedtype S
}

// First implementation of SeniorProtocol
struct SeniorImpl1:SeniorProtocol {
    typealias S = BaseProtocol
    init() {}
}

// Second implementation of SeniorProtocol
struct SeniorImpl2:SeniorProtocol {
    typealias S = BaseProtocol
    init() {}
}

// The function 
func whichImpl<T: SeniorProtocol>() -> T{
    if Int.random(in: 0 ... 5) < 3 {
        return SeniorImpl1() as! T
    }
    else {
        return SeniorImpl2() as! T
    }
}

Finally, when I run最后,当我跑步时

var c = whichImpl()

I got this error: “Generic parameter 'T' could not be inferred”.我收到此错误:“无法推断通用参数'T'”。 It seems that the compiler does't know what T is.似乎编译器不知道 T 是什么。 How can I solve it?我该如何解决? I just want to do what the code written in whichImpl()我只想做whichImpl()中写的代码

Since your method returns a value of the generic type T, then you have to let Swift know which concrete type you want your c variable to be to make Swift's type checking system works.由于您的方法返回泛型类型 T 的值,因此您必须让 Swift 知道您希望c变量成为哪个具体类型,以使 Swift 的类型检查系统正常工作。 In your case, simply give your c a concrete type like this will make the error pass away.在您的情况下,只需为您的c提供一个像这样的具体类型将使错误消失。

var c: Int = whichImpl()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM