Tajnero
Tajnero

Reputation: 593

Not specifying type in generic for Swift class

Let's say we have one protocol:

protocol Animal {
}

two class which implement this protocol:

class Dog: Animal {
}

class Bear: Animal {
}

and generic which uses this protocol:

class A<T: Animal> {
}

Now I can create another classes:

class B: A<Dog> {
}

class C: A<Bear> {
}

I hope you understand case. And now we have protocol which has instance of class A as parameter:

protocol SomeProtocol {

    func something(a: A)
}

and I want to implement this protocol in class e.g. D.

class D: SomeProtocol {

    func something(a: A) {
    }
}

But it won't compile because we have to specify generic for A, how can we do that if we want to send in this parameter instance of class B or C? Can I somehow omit generic in this function?

Upvotes: 2

Views: 386

Answers (1)

Hamish
Hamish

Reputation: 80781

Can I somehow omit generic in this function?

No, you currently cannot talk in terms of a generic type without its placeholder(s). However, you can simply introduce a new local generic placeholder to the function, allowing the placeholder to be satisfied at the call-site.

protocol SomeProtocol {
    func something<T>(a: A<T>)
}

class D : SomeProtocol {
    func something<T>(a: A<T>) {
        // ...
    }
}

In the case of passing in an instance of B, T will be Dog. In the case of passing in an instance of C, T will be Bear.

Upvotes: 3

Related Questions