通过NSDate检查值是否存在为字典中的键

pho*_*sis 3 ios swift

我有一个这样的字典:

var dic = [NSDate: Int]()
Run Code Online (Sandbox Code Playgroud)

它在我的iOS待办事项应用程序中用于获取特定日期的已完成任务的数量.我只关心NSDate中的年,月和日部分,并希望能够使用这个字典获得特定日期的任务数量,我该怎么做?谢谢.

Vis*_*kar 5

您可以将其保存为字典,而不是将日期作为NSDate存储在字典中,以便比较更容易.使用以下代码将其存储为字符串

func dateFromString(date : NSDate) -> String {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    return dateFormatter.stringFromDate(date)
}
Run Code Online (Sandbox Code Playgroud)

您可以将NSDate()传递给上面的函数,它将为您提供仅包含年,月和日期的字符串.要从字典中检索数据,请使用以下内容.

func dateFrom(year:Int, month:Int, day:Int) -> String {
    let components = NSDateComponents()
    components.year = year
    components.month = month
    components.day = day

    let gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
    let date = gregorian!.dateFromComponents(components)
    return dateFromString(date!)
}
Run Code Online (Sandbox Code Playgroud)

您可以将年,月和日期传递给上述函数,它将以字符串格式返回相应的日期.所以你的字典操作会是这样的

 dict[dateFromString(NSDate())] = 1 //for insertion or updation
 let numOfTasks = dict[dateFrom(2016, month: 1, day: 15)] //to get task for any particular day
Run Code Online (Sandbox Code Playgroud)

编辑

如果要继续使用NSDate作为字典的密钥,则必须按如下方式修改上述代码.dateFrom将返回您选择的年,月和日期的日期,时间将是一些常量值.如果您未设置,则时间将设置为当前时区的午夜.

func dateFrom(year:Int, month:Int, day:Int) -> NSDate {
    let components = NSDateComponents()
    components.year = year
    components.month = month
    components.day = day
    let gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
    let date = gregorian!.dateFromComponents(components)
    return date!
}
Run Code Online (Sandbox Code Playgroud)

并获取当前日期使用,以便将当前年份,日期,月份和时间的日期对象存储到某个常量值.

func getCurrentDate()->NSDate {
    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components([.Day , .Month , .Year], fromDate: date)

    return dateFrom(components.year, month: components.month, day: components.day)
}
Run Code Online (Sandbox Code Playgroud)

用法如下

dict[getCurrentDate()] = i //for insertion or updation
let numOfTasks = dict[dateFrom(2016, month: 1, day: 15)] //to get task for any particular day
Run Code Online (Sandbox Code Playgroud)