Can an array of a superclass `EKCalendarItem` store elements that are subclassed, like `EKEvent` and `EKReminder`

44 Views Asked by At

I have a calendar viewer in which I would like to use a combination of calendar-events and reminder-events.

Just as Apple provides two different first-party apps, internally, the two are different classes.

But they both sub-class EKCalendarItem

I was hoping I could do something like:

listForCalendarTable:[EKCalendarItem] = []

And then latter add various EKEvent and EKReminder, because they are both subclasses EKCalendarItem.

When I try this, it seems to silently discard

(Here's code I put into a Swift Playground)

        var superClassArray:[EKCalendarItem] = []

        let reminder = EKReminder()
        print (reminder)
        let calEvent = EKEvent()
        print (calEvent)

        superClassArray.append(reminder)
        superClassArray.append(calEvent)
        print (superClassArray)
1

There are 1 best solutions below

0
clawesome On

Your use of an array of a superclass with multiple subclass types is fine, the problem with your code is the initialization of your EKReminder and EKEvent objects, both of which need to be passed an EKEventStore to be created:

    var superClassArray:[EKCalendarItem] = []

    var eventStore = EKEventStore()
    
    var reminder = EKReminder.init(eventStore: eventStore)
    print (reminder)
    let calEvent = EKEvent.init(eventStore: eventStore)
    print (calEvent)
    
    superClassArray.append(reminder)
    superClassArray.append(calEvent)
    print (superClassArray)