2

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!

dor506
  • 5,246
  • 9
  • 44
  • 79
  • 1
    Possible duplicate of [Unable to use protocol as associatedtype in another protocol in Swift](http://stackoverflow.com/questions/37360114/unable-to-use-protocol-as-associatedtype-in-another-protocol-in-swift) – Hamish Dec 01 '16 at 10:52

1 Answers1

2

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>

Vader
  • 77
  • 1
  • 7