简体   繁体   中英

Protocols with associated type in Swift 3

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?

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 String s 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM