简体   繁体   中英

How to make one protocol with a property that is another protocol, yet ensure that classes which conform to the first protocol can be restricted

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 , eg 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. 
}

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 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM