Ryan Hampton Ryan Hampton - 8 months ago 73
iOS Question

Swift: NSDate.day returning nil

I am trying to access a NSDate variable stored within coredata as AnyObject and print the day. When I print it, it returns nil. When I print the Date without .day after it it prints the correct value.
Edit: workoutDate is an attribute of the entity 'Workout' and is of type 'Date'

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext

do {
let request = NSFetchRequest(entityName: "Workout")
let results = try context.executeFetchRequest(request)

if results.count > 0 {
for item in results as! [Workout]{

let time = item.valueForKey("workoutTime")
let currentWorkoutDate = item.valueForKey("workoutDate")
let workoutDateDay = currentWorkoutDate!


NSDate has no day property. However, the Key-Value coding method

let currentWorkoutDate = item.valueForKey("workoutDate")

returns an AnyObject? and you can call any (existing) Objective-C method on that object (compare The strange behaviour of Swift's AnyObject). The compiler does not complain because day is a property of NSDateComponents. But at runtime, it is detected that the object does not respond to this property, and therefore workoutDateDay.day is nil.

The solution is to convert the value to an NSDate object:

if let workoutDate = item.valueForKey("workoutDate") as? NSDate {
    // ...

or better, create a NSManagedObject subclass for the entity and use the property accessors.

Then use the NSCalender methods to get NSDateComponents from the date, for example

if let workoutDate = item.valueForKey("workoutDate") as? NSDate {
    let day = NSCalendar.currentCalendar().component(.Day, fromDate: workoutDate)
    // ...