Woodman
Woodman

Reputation: 1512

Setting up a two week timetable in Swift

NOTE: I am a new Swift programmer, a NOOB if you will.

I am creating a school timetable app just for personal use to practise my coding. However, our school operates on a two week time table system, with 10 days, labeled 1 through to ten. I am wondering if anyone had some ideas as to how I could work out whether the current date is day one or day nine or day 4. I know I could use if statements for the dates, but the would take a long time, and require manual input of the dates. How could I have the app keep count of what day it is, skipping weekends? EDIT - I could maybe have 14 days, with days 6,7,13 and 14 empty.

FOR EXAMPLE: The current date is OCT 4, this is day one. I would like the app to be able to work out what day of the timetable the current date is. This would then load the appropriate day (e.g. Subject, Teacher, Classroom). Day One is Monday, Two is Tuesday, Five is Friday, Six is Monday, 10 is Friday. Could I have some sort of rostering system?

I am sorry if the question is vague, please tell me if I need to clarify. I have been working on a fix for weeks now, so I have decided to turn to help. Any guidance whatsoever would be much appreciated, as I am at a dead end!

Many thanks

Upvotes: 0

Views: 803

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31016

The numbers that I'm plugging into this example probably don't match your requirements but consider this as a strategy. (In this case, using a 1-to-14 cycle. If you'd rather get 1-to-10 you can put in a subtraction and a different error to throw on the "bad" days.)

class CyclicDay {

    enum CyclicDayError: ErrorType {
        case InvalidStartDate
    }

    lazy var baseline: NSDate? = {

        // Set up some start date that matches day 1
        var components = NSDateComponents()
        components.day = 6
        components.month = 9
        components.year = 2015
        return NSCalendar.currentCalendar().dateFromComponents(components)
    }()

    func dayOfCycle(testDate: NSDate) throws -> Int {
        if let start = baseline {

            // Convert difference to days
            let interval = testDate.timeIntervalSinceDate(start)
            let days = interval / (60 * 60 * 24)

            // Convert to value 1..14 to position in a 2-week cycle
            return Int(days % 14) + 1
        }
        throw CyclicDayError.InvalidStartDate
    }
}

// Test today
let cd = CyclicDay()
let day = try cd.dayOfCycle(NSDate())

Upvotes: 1

Related Questions