0

Essentially, my end goal is to have one protocol Log which enforces that all objects which conform to it have an array of objects that conform to another protocol [LogEvent].

However, the classes which conform to Log need to have specific types of LogEvent, e.g. NumericalLogEvent, in the events array, not the more general LogEvent.

I'm getting the error "Type 'NumericalLog' does not conform to protocol 'Log'" when I try to use the code below.

How do I ensure that everything that conforms to log has some events array of type LogEvent, yet leave it open as to exactly which type that is?

protocol Log {
    var events: [LogEvent] { get set } // Want to enforce events here
}

protocol LogEvent {
    timeStamp: Date { get set }
}

struct NumericalLogEvent: LogEvent {
    timeStamp: Date
    value: Float
}

class NumericalLog: Log {
    var events: [NumericalLogEvent]

    // But getting error here when trying to use more specific type. 
}
James Mulholland
  • 1,782
  • 1
  • 14
  • 21
  • Compare https://stackoverflow.com/q/42561685/2976878. Sounds like you want an `associatedtype` here. – Hamish Jan 26 '18 at 11:41

1 Answers1

1

Got it!

The trick is to set an associatedtype (the equivalent of a generic for protocols) and then to set this as the type in events.

protocol Log {
    associatedtype Event: LogEvent

    var events: [Event] { get set }
}
James Mulholland
  • 1,782
  • 1
  • 14
  • 21