whatiwunder
whatiwunder

Reputation: 1

Write an instance method advance the time by those minutes

I am new to swift and I am teaching myself. I know it's customary to have sample code but I'm extremely lost. I'm trying to write an instance method advance that will be placed inside the ClockTime class. The method accepts a number of minutes as its parameter and moves your object forward in time by that amount of minutes. The minutes passed could be any non-negative number, even a large number such as 500 or 1000000. If necessary, your object might wrap into the next hour or day, or it might wrap from the morning ("AM") to the evening ("PM") or vice versa.

Note: A ClockTime object doesn't care about what day it is; if you advance by 1 minute from 11:59 PM, it becomes 12:00 AM.

For example, the following calls would produce the following results:

ClockTime time = new ClockTime(6, 27, "PM");

time.advance(1);       //  6:28 PM

time.advance(30);      //  6:58 PM

Upvotes: 0

Views: 170

Answers (1)

Mark
Mark

Reputation: 7409

You probably want something like this:

struct ClockTime {
    var hour: Int {
        return components.hour!
    }
    var minute: Int {
        return components.minute!
    }

    private var internalTime = Date()
    private var components: DateComponents {
        return Calendar.current.dateComponents([.hour, .minute], from: internalTime)
    }

    mutating func advance(by minutes: TimeInterval) {
        internalTime.addTimeInterval(minutes * 60)
    }
}

Upvotes: 1

Related Questions