1

I stuck with Swift syntax. This code example won't compile and i can't find why. It says

Type 'TextMessageViewModelDefaultBuilder' does not conform to protocol 'ViewModelBuilderProtocol'

import Foundation

protocol MessageModelProtocol { }
protocol MessageViewModelProtocol { }

protocol TextMessageViewModelProtocol:MessageViewModelProtocol {}
protocol TextMessageModelProtocol:MessageModelProtocol {}

protocol ViewModelBuilderProtocol {
    associatedtype ModelT: MessageModelProtocol
    associatedtype ViewModelT: MessageViewModelProtocol
    func canCreateViewModel(fromModel model: Any) -> Bool
    func createViewModel(_ model: ModelT) -> ViewModelT
}

class TextMessageViewModelDefaultBuilder: ViewModelBuilderProtocol {
    typealias ModelT = TextMessageModelProtocol
    typealias ViewModelT = TextMessageViewModelProtocol

    init() {}

    func createViewModel(_ textMessage: ModelT) -> ViewModelT {
        return ViewModelT()
    }

    func canCreateViewModel(fromModel model: Any) -> Bool {
        return model is ModelT
    }
}
surfrider
  • 1,376
  • 14
  • 29
  • 2
    Compare [Unable to use protocol as associatedtype in another protocol in Swift](https://stackoverflow.com/q/37360114/2976878) & [Protocol doesn't conform to itself?](https://stackoverflow.com/q/33112559/2976878) – Hamish May 29 '18 at 10:39
  • Hmm so the reason is i can't use `protocol` types to implement requirement of `associatedtype`? Only concrete type? – surfrider May 29 '18 at 11:02
  • 1
    You cannot currently satisfy a placeholder type that's constrained to some protocol with a (non-`@objc`) protocol type, as such protocols do not conform to themselves (the reason why this is the case is explained in the above Q&As I linked to). Specifically in your example, `TextMessageModelProtocol` is not a type that conforms to `MessageModelProtocol`, despite deriving from it. – Hamish May 29 '18 at 11:12
  • Thanks. I will investigate into this. On first look it's very weird restriction. – surfrider May 29 '18 at 11:28

1 Answers1

-1

Hamish in comments pointed to that fact that in Swift protocols doesn't conforms to themselves. Thus i can't use protocol types to implement requirement of associatedtype.

surfrider
  • 1,376
  • 14
  • 29