[英]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
本质上,我的最终目标是拥有一个协议Log
,该Log
强制所有符合该协议的对象都具有一个符合另一协议[LogEvent]
的对象数组。
然而,这符合班Log
需要有特定类型LogEvent
,如NumericalLogEvent
,中events
数组,而不是更一般LogEvent
。
尝试使用以下代码时,出现错误“ Type'NumericalLog'类型不符合协议'Log'”错误。
如何确保符合日志的所有内容都有一些 LogEvent类型的事件数组,而对于确切的类型却保持打开状态?
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.
}
得到它了!
技巧是设置一个associatedtype
(与协议的泛型等效),然后将其设置为events
的类型。
protocol Log {
associatedtype Event: LogEvent
var events: [Event] { get set }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.