我正在和EventKit's
EKEventStore
一起工作,我想模仿它,同时也模仿EKEvent。
但我不知道如何正确地抽象和其他方法。
protocol EventStoring {
associated type Event: EventStoreEvent where Event.MatchingEventStore == Self
func save(_ event: Event, span: EKSpan, commit: Bool) throws
// Other methods of EKEventStore I use
}
extension EKEventStore: EventStoring {
typealias Event = EKEvent
}
protocol EventStoreEvent {
associatedtype MatchingEventStore: EventStoring
static func createEvent(eventStore: MatchingEventStore) -> Self
}
extension EKEvent: EventStoreEvent {
typealias MatchingEventStore = EKEventStore
static func createEvent(eventStore: MatchingEventStore) -> Self {
return EKEvent(eventStore: eventStore) as! Self
}
}
这里的错误是:“Self”只在协议中可用,或者是作为类中方法的结果;您的意思是
EKEvent's
并且:“无法将
init(eventStore: EKEventStore)
类型的返回表达式转换为返回类型'Self'”class GenericEventManger<StoreEvent: EventStoreEvent> {
var store: EventStoring
required init(with eventStore: EventStoring) {
self.store = eventStore
}
func createEvent() -> StoreEvent {
let eventStoreEvent: EventStoreEvent = StoreEvent.createEvent(eventStore: store)
// Then some code where I configure the event...
try store.save(eventStoreEvent, span: .thisEvent, commit: true)
}
}
最后一行的第七个错误是:不能用
'EKEvent'
类型的参数列表调用'EKEvent'
最后一个是:不能用
'createEvent'
类型的参数列表调用“save”由于我修改了Dan的建议,所以在我的实现中出现了另一个类似的问题,所以我更新了我的问题
最佳答案
我想在丹的帮助下,我找到了其中两个问题的解决方案,但我还没有彻底测试:
首先我改变了store
属性的类型,就像Dan推荐的那样
class GenericStoreManger<StoreEvent: EventStoreEvent> {
var store: StoreEvent.MatchingEventStore
func createEvent() -> StoreEvent {
let eventStoreEvent: EventStoreEvent = StoreEvent.createEvent(eventStore: store)
// Then some code where I configure the event...
try store.save(eventStoreEvent as! StoreEvent.MatchingEventStore.Event, span: .thisEvent, commit: true)
}
...
}
然后我改变了如何在
GenericStoreManager
中获取返回值,这样它也可以在EKEvent的子类中工作extension EKEvent: EventStoreEvent {
typealias MatchingEventStore = EKEventStore
static func createEvent(eventStore: MatchingEventStore) -> Self {
return self.init(eventStore: eventStore)
}
}
关于swift - 如何解决“无法使用类型为'(eventStore:EventStoring)'的参数列表调用'createEvent'”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54406371/