【问题标题】:Swift associatedType from protocol type - how to do that?来自协议类型的 Swift associatedType - 怎么做?
【发布时间】:2017-06-27 17:46:54
【问题描述】:

我在使用关联类型作为协议时遇到问题:

protocol Searchable{    
    func matches(text: String) -> Bool
}

protocol ArticleProtocol: Searchable {
    var title: String {get set}
}

extension ArticleProtocol {
    func matches(text: String) -> Bool {
        return title.containsString(text)
    }
}

struct FirstArticle: ArticleProtocol {
      var title: String = ""
}

struct SecondArticle: ArticleProtocol {
      var title: String = ""
}

protocol SearchResultsProtocol: class {    
    associatedtype T: Searchable
}

当我尝试实现搜索结果协议时,出现编译问题:

"类型 SearchArticles 不符合协议 SearchResultsProtocol"

class SearchArticles: SearchResultsProtocol {
   typealias T = ArticleProtocol
}

据我了解,这是因为 SearchArticles 类中的 T 不是来自具体类型(该示例中为结构),而是来自协议类型。

有没有办法解决这个问题?

提前致谢!

【问题讨论】:

标签: swift generics associated-types


【解决方案1】:

associatedtype 不是占位符(协议),而是具体类型。通过在类声明中添加泛型,您可以像这样实现您想要的相同结果....

class SearchArticles<V: ArticleProtocol>: SearchResultsProtocol {
    typealias T = V
}

然后,当您在应用周围使用SearchArticles 时,您可以声明let foo = SearchArticles&lt;FirstArticle&gt;let foo = SearchArticles&lt;SecondArticle&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-14
    相关资源
    最近更新 更多