Protocols with associated type in Swift 3

389 views Asked by At

I found out that associated types complicates a little bit Swift for me, especially because I keep in mind Java approach.

My problem is that I want to create simple interface (oh, right, protocol) which could look like this:

protocol Sender {

    associatedtype Data

    func send(data: Data)
}

In Java it would look like this:

class Sender<T> {

     void send(T data);

}

And now I want to use this protocol as method parameter, but I don't know how I can do it in Swift, but in Java it would look like this ;) (String type as example)

void addSender(Sender<String> sender) {
      // do something
}

So how can I achieve this using Swift?

1

There are 1 answers

0
Keiwan On

You could write something like

func addSender<T: Sender>(_ sender: T) where T.Data == String {

}

I'm not sure if there's a shorter alternative to make this work.

A Sender implementation for Strings could look like this:

class StringSender : Sender {
    //typealias Data = String      <- This can be inferred from the parameter type of send

    func send(data: String) {
        // Send a string
    }
}