ios – Swift – Injecting and storing protocols


Discover that the parse implementation requires that the mapper has T == Knowledge and U == Monitor, however you have not specified these constraint anyplace in TrackParser.

We are able to make T and U the main related sorts of MapperProtocol, in order that the same-type necessities may be specified very simply as MapperProtocol<Knowledge, Monitor>.

protocol MapperProtocol<T, U> { // Discover the "<T, U>"
    associatedtype T
    associatedtype U
    func map(merchandise: T) -> U?

Additionally, ranging from Swift 5.7, existential sorts are required to be prefixed with “any“, so you’d write:

non-public let mapper: any MapperProtocol<Knowledge, Monitor>

init(mapper: any MapperProtocol<Knowledge, Monitor>) {
    self.mapper = mapper


Leave a Reply