Andrei Krotov
Andrei Krotov

Reputation: 306

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:

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.

Upvotes: 0

Views: 96

Answers (2)

EmilioPelaez
EmilioPelaez

Reputation: 19912

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.

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.

If you give us a more real-life example, we might be able to help you find a better solution.

Upvotes: 1

PGDev
PGDev

Reputation: 24341

Use TestProtocol.Type instead of TestType.Type, i.e.

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

Upvotes: 1

Related Questions