How to require a generic type implement a generic protocol using a specific type in the protocol

generics, ios, protocols, swift

Solution

Prototypes don't seem to have generics the way classes and structs do in Swift, but you can have associated types with `typealias`, which are close.

You can use type constraints to make sure that the object you pass in adopts the `Proto` with type constraints. To make the `Proto` you pass into `require` has the right `B`, you use `where`.

Apples documentation on generics has a lot of info.

This blog post is also a good source of info on doing more complicated things with generics.

protocol Proto {
    typealias B
    func someFunction()
}

class SampleClass {}

class Conforms : Proto {
    typealias B = SampleClass
    func someFunction() { }
}

class TestingClass {
    func requires<T: Proto where T.B == SampleClass>(param: T) {
        param.someFunction()
    }
}

Problem

Hi I'm using generics a lot in my current project. However, I've come across a problem: I need a generic function `foo<T>` to be able to take a parameter that conforms to a generic protocol using a specific type. For example in Java I can do: ``` public interface Proto<B> { public void SomeFunction() } public class SampleClass { } public class Conforms extends Proto<SampleClass> { @Override public void SomeFunction () {} } public class TestingClass { public void Requires (Proto<SampleClass> param) { // I can use param } } ``` How would I do the same `Requires()` function in Swift? I know in Swift you use `typealias` in the protocol for generics. How do I constrain a parameter based on the `typealias`?

Original source

Related problems