maniacus
maniacus

Reputation: 381

Swift Generics (type substitution?)

It's an isolated example, so may look less useful, but I was wondering anyway, why it doesn't work? Any insight much appreciated.

protocol Prot: class {
    init()
}

class A: Prot {
    required init(){ }
}

struct Client<T: Prot> {
    let tau: T.Type
}

if let aTau = A.self as? Prot.Type {
    print(aTau === A.self)  // ✅
    Client(tau: A.self)     // ✅
    Client(tau: aTau)       // ❌
}

The error is:

Cannot invoke initializer for type 'Client<_>' with an argument list of type '(tau: Prot.Type)'

Upvotes: 3

Views: 83

Answers (1)

Cristik
Cristik

Reputation: 32787

The generic Client class needs a concrete type for specialization - i.e. a class/struct/enum, and Prot.Type doesn't fit this requirement. This is why you get the error.

Upvotes: 2

Related Questions