Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift associatedType来自协议类型-如何做到这一点?_Swift_Generics_Associated Types - Fatal编程技术网

Swift associatedType来自协议类型-如何做到这一点?

Swift associatedType来自协议类型-如何做到这一点?,swift,generics,associated-types,Swift,Generics,Associated Types,我在使用关联类型作为协议时遇到问题: protocol Searchable{ func matches(text: String) -> Bool } protocol ArticleProtocol: Searchable { var title: String {get set} } extension ArticleProtocol { func matches(text: String) -> Bool { return

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

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”

据我所知,之所以发生这种情况,是因为SearchArticles类中的T不是来自具体类型(在该示例中为struct),而是来自协议类型

有没有办法解决这个问题


提前谢谢

关联类型不是占位符(协议),而是具体类型。通过向类声明中添加泛型,您可以获得如下所示的相同结果

class SearchArticles<V: ArticleProtocol>: SearchResultsProtocol {
    typealias T = V
}
class SearchArticles:SearchResultsProtocol{
类型别名T=V
}
然后,当您在应用程序中使用
SearchArticles
时,您可以声明
let foo=SearchArticles
let foo=SearchArticles

可能重复的
class SearchArticles<V: ArticleProtocol>: SearchResultsProtocol {
    typealias T = V
}