Search code examples
iosswiftcore-dataanyobject

Converting AnyObject? to NSDate


I am trying to fetch scores (NSDates) from core data and return a date. Returning 00:00:00.00 if the coreData is empty and displaying the first date if it isn't.

I have the following code:

func getHighScore() -> NSDate {
    let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let context = appDel.managedObjectContext

    var entity = NSFetchRequest(entityName: "Score")
    entity.returnsObjectsAsFaults = false


    var score = NSFetchRequest(entityName: "Score")
    score.returnsObjectsAsFaults = false

    let results: [AnyObject]
    results = context!.executeFetchRequest(score, error: nil)!
    println("\(results.count) scores available")

    dateFormatter.dateFormat = "HH:mm:ss.SS"
    var highScore : NSDate = dateFormatter.dateFromString("00:00:00.00")!

    if (results.count>0){
            var time: AnyObject? = results[0].valueForKey("time")
            println(time)
            var highScore = time as NSDate


        return highScore
    }
    else {
        return dateFormatter.dateFromString("00:00:00.00")!
    }
}

When i try the line:

var highScore = time as NSDate

I get the error 'AnyObject? isn't convertible to NSDate', when i force the downcast and it changes to:

var highScore = time as! NSDate

I get the error 'fatal error: unexpectedly found nil while unwrapping an Optional value'.

Any help would be appreciated :)


Solution

  • It looks like time is nil.

    Try if let hs = time as? NSDate{ highscore = hs}