简体   繁体   English

迅速。 不能使用类型变量作为泛型方法的规范

[英]Swift. Can't use Type variable as specification to generic method

I try to make a generic method in Swift without an object of a generic type with this code:我尝试使用以下代码在 Swift 中创建一个没有泛型类型对象的泛型方法:

protocol TestProtocol {}

class TestClass1: TestProtocol {}
class TestClass2: TestProtocol {}
class TestClass3: TestProtocol {}
class TestClass4: TestProtocol {}

enum TestEnum {
    case one, two, three, four
    
    var type: TestProtocol.Type {
        switch self {
        case .one: return TestClass1.self
        case .two: return TestClass2.self
        case .three: return TestClass3.self
        case .four: return TestClass4.self
        }
    }
}

class TestMethods {
    func prepareToGet(kind: TestEnum) {
        getTest(as: kind.type)
    }
    
    func getTest<TestType: TestProtocol>(as: TestType.Type) {
      // here I need specified type of TestProtocol to handle it
    }
}

But with Type variable.但是带有类型变量。 But I have errors:但我有错误:

Cannot convert value of type 'TestProtocol.Type' to expected argument type 'TestType.Type'

Generic parameter 'TestType' could not be inferred

I feel blind, but I really don't see the problem.我感到盲目,但我真的没有看到问题。

使用TestProtocol.Type而不是TestType.Type ,即

func getTest(as type: TestProtocol.Type) {}

My understanding is that you want the function to know the class of the generic by using information from the enum, but generic functions need to be able to infer the type at compile time, and the result of TestEnum.type is only available at run time.我的理解是,你希望函数通过使用枚举的信息来知道泛型的类,但是泛型函数需要能够在编译时推断出类型,而TestEnum.type的结果只有在运行时才可用.

I'm not sure what the real case scenario you have, but I think that the best you can do is to have a function that returns TestProtocol , either as a type or object, whatever you need, and conditionally cast it to the type you want.我不确定您拥有的实际情况是什么,但我认为您能做的最好的事情是拥有一个返回TestProtocol的函数,无论您需要什么类型或对象,并有条件地将其TestProtocol为您的类型想。

If you give us a more real-life example, we might be able to help you find a better solution.如果您给我们提供一个更真实的例子,我们或许可以帮助您找到更好的解决方案。

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

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