如何跟踪随日期移动的数据?

How can I keep track of data moving with dates?

我有一个学校应用程序可以跟踪您的日程安排。该应用程序有多种输入时间表的选项。如果用户有四天的日程安排,那么他们将有 A-D 天。对于我的应用程序。我想跟踪当前日期(例如,是 A 日还是 C 日)。用户将能够在他们设置应用程序时指定是哪一天,但是应用程序应该每天跟踪此更改,周末除外。我不确定实现它的最佳方法是什么。

如果配置允许完全任意的日期分配,您只需要一个 [Date:String] 形式的简单字典。

如果您想让您的用户指定日期标识符(字母)的重复模式,则配置参数和过程将需要更加复杂,并且取决于您愿意在处理异常方面走多远(即非上学日)。周末可以是自动的,但假期和预定 "off days" 需要您定义某种规则(硬编码或用户可配置)。

在所有情况下,我建议创建一个函数,根据配置的参数将任何日期转换为其日期标识符。根据规则的复杂性和您正在使用的日期范围,动态构建日期标识符的全局字典(例如 [Date:String])并且每个日期只计算一次标识符可能是个好主意。

例如:

// your configuration parameters could be something like this:

let firstSchoolDay:Date     = // read from configuration
let lastSchoolDay           = // read from configuration
let dayIdentifiers:[String] = // read from configuration 
let skippedDates:Set<Date>  = // read from configuration 

// The global dictionary and function could work like this:

var dayIdentifiers:[Date:Sting] = [:] // global scope (or singleton)
func dayIdentifier(for date:Date) -> String
{
    if let dayID = dayIdentifiers[date]
    { return dayID  }

    let dayID:String = // compute your day ID once according to parameters.
                       // you could use an empty string as a convention for
                       // non school days

                       // a simple way to compute this is to start from
                       // the last computed date (or firstSchoolDay)
                       // and move forward using Calendar.enumerateDates
                       // applying the weekend and offdays rules
                       // and saving day identifiers as you
                       // move forward up to the requested date

    dayIdentifiers[date] = dayID
    return dayID         
}

我想出了如何跟踪搬家日期,同时又不考虑周末并在每次检查时更新值。

func getCurrentDay() -> Int {

    let lastSetDay = //Get the last value of the set day
    let lastSetDayDate = //Get the last time the day was set
    var numberOfDays: Int! //Calculate number of recurring days, for instance an A, B, C, D day schedule would be 4

    var currentDay = lastSetDay
    var currentIteratedDate = lastSetDayDate

    while Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
        currentIteratedDate = Calendar.current.date(byAdding: .day, value: 1, to: currentIteratedDate)!
        if !Calendar.current.isDateInWeekend(currentIteratedDate) {
            currentDay += 1
        }
        if currentDay > numberOfDays {
            currentDay = 1
        }
    }

    if Calendar.current.isDate(currentIteratedDate, inSameDayAs: Date()) == false {
        //Save new day
        //Save new date
    }

    return currentDay
}