Protocols with associated type in Swift 3

Question

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?


Show source
| generics   | java   | swift   | associated-types   2017-01-07 10:01 1 Answers

Answers ( 1 )

  1. 2017-01-07 11:01

    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
        }
    }
    
◀ Go back