本质上,我的最终目标是拥有一个协议(protocol) Log
,它强制所有符合它的对象都有一个符合另一个协议(protocol) [LogEvent]
的对象数组.
但是,符合Log
的类需要有特定类型的LogEvent
,Ví dụNumericalLogEvent
,hiện hữu events
数组中,而不是更通用的 LogEvent
.
当我尝试使用下面的代码时,出现错误“类型‘NumericalLog’不符合协议(protocol)‘Log’”。
我如何确保符合日志的所有内容都具有 Một số 类型为 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
(相当于协议(protocol)的泛型),然后将其设置为events
中的类型。
protocol Log {
associatedtype Event: LogEvent
var events: [Event] { get set }
}
Tôi là một lập trình viên xuất sắc, rất giỏi!