Generic Function With Class Type Argument

Viewed 41

I want to store a generic class type in an enum and be able to pass it into a function.

protocol SomeProtocol {}

class FirstClass: SomeProtocol {}
class SecondClass: SomeProtocol {}

enum SomeEnum {
    case one
    case two

    var protocolType: SomeProtocol.Type {
        switch self {
        case .one: return FirstClass.self
        case .two: return SecondClass.self
        }
    }
}

func doSomething<T: SomeProtocol>(protocolType: T.Type) {
    // do some stuff...
}

Why does this compile:

doSomething(protocolType: FirstClass.self)

But this doesn't?

doSomething(protocolType: SomeEnum.one.protocolType)

The latter gives this compile error: Cannot convert value of type 'SomeProtocol.Type' to expected argument type 'T.Type'

0 Answers
Related