dor506
dor506

Reputation: 5414

Swift associatedType from protocol type - how to do that?

I'm having issues using associated type as protocol:

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
}

When I try to implement search results protocol, I get compile issue:

"type SearchArticles does not conform to protocol SearchResultsProtocol"

class SearchArticles: SearchResultsProtocol {
   typealias T = ArticleProtocol
}

As I understand, it happens because T in SearchArticles class is not from concrete type (struct in that example), but from protocol type.

Is there a way to solve this issue?

Thanks in advance!

Upvotes: 2

Views: 500

Answers (1)

Vader
Vader

Reputation: 77

An associatedtype is not meant to be a placeholder (protocol), it is meant to be a concrete type. By adding a generic to the class declaration you can achieve the same result you want like this....

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

Then, as you use SearchArticles around your app, you can declare let foo = SearchArticles<FirstArticle> or let foo = SearchArticles<SecondArticle>

Upvotes: 2

Related Questions