Home > Software design >  Initialize a Child Class from an instance of Parent class Swift
Initialize a Child Class from an instance of Parent class Swift

Time:09-02

I am kind of new to OOP (I think I understand the basics now), so I'm struggling with something:
I am currently making a personal iOS app that involves using events from the iPhone Calendar. I wanted to add properties to the built in EKEvent class but I read that's not possible with extensions.
So I decided to make my own Class, called Event, that will inherit from EKEvent and add the properties I want.

But I'm struggling with the initialization for this class: I would like to initialize Event from an instance of EKEvent since I'm getting EKEvents when I fetch the events of my Calendar, but I can't find a way to do it. I looked but didn't find a similar questions for Swift, they are using super.init() which is not what I want to do.

Here's my class, I found a workaround as you can see but I'd like to understand how to do it with inheritance if it's possible ^^

class Event {    // Deleted the : EKEvent here to test my workaround
    public var matiere: String = ""
    public var matiereId: String = ""
    public var prof: String = ""
    public var salle: String = ""
    public var type: String = ""
    
    public var ekEvent: EKEvent
    public var duration: DateInterval
    public var hoursDuration: Int
    public var minutesDuration: Int
    
    init(ekEvent: EKEvent) {
        /* Here is my workaround, if I need to access properties from EKEvent I'll use
        self.ekEvent.startDate (for example) */
        self.ekEvent = ekEvent

        self.duration = DateInterval(start: ekEvent.startDate, end: ekEvent.endDate)
        
        self.hoursDuration = Int(duration.duration) / 3600
        self.minutesDuration = (Int(self.duration.duration) - (3600 * self.hoursDuration)) / 60
    }
    
}

Thanks in advance and excuse my English I'm French =D

CodePudding user response:

glad to hear you're getting into OOP!

So the way you've seen people doing this using super.init() is the most common and accepted way to achieve what you want, but in this case, the init function that you would want to override hasn't been marked as open.

This essentially means you can't override it and init your own variables, then call super.init. So your approach is completely fair in this case.

Streamline the process

so, as an idea, if you're aiming to try and make this a little more streamline, you could do something like this:

extension EKEvent {
    
    func createEvent() -> Event {
        .init(ekEvent: self)
    }
    
}

This will allow you to now do this: ekEvent.createEvent() and then this will return an event object which you can use.

  • Related