简体   繁体   English

Swift 3中具有关联类型的协议

[英]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. 我发现关联类型对我来说让Swift变得有些复杂,尤其是因为我牢记Java方法。

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: 在Java中,它看起来像这样:

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) 现在,我想将此协议用作方法参数,但是我不知道如何在Swift中完成此操作,但是在Java中,它看起来像这样;)(以字符串类型为例)

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

So how can I achieve this using Swift? 那么如何使用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: StringSender实现可能如下所示:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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