Search code examples
swiftcore-datansdate

Convert NSDate to Date


this might be a stupid question, but I can´t find the information. I'm using CoreData in my app, and I save an array of structs. The problem is when I fetch and try to restore it into the struct array, I have a problem with my Date variable; I can't find a way to convert it from NSDate to Date, I try using as Date, but it makes me force downcast and I'm not sure if it's safe. Is it correct? or is there another way?

This is my Struc:

struct MyData {
        var value = Int()
        var date = Date()
        var take = Int()
        var commnt = String()
    }

This is how I'm fetchin the data:

func fetchRequestInfo() -> [MyData] {

        let fetchRequest: NSFetchRequest<GlucoseEvents> = GlucoseEvents.fetchRequest()

        do {
            let searchResults = try DatabaseController.getContext().fetch(fetchRequest)

            for result in searchResults as [GlucoseEvents] {
               let value = Int(result.value)
               let date = result.date as Date
               let take = Int(result.take)
               let commnt = String(describing: result.commnt)
                let data = MyData(value: value, date: date, take: take, commnt: commnt)
               self.dataArray.append(data)
                }



            } catch {

                print ("error: \(error)")

            }
        let orderArray = self.dataArray.sorted(by: { $0.date.compare($1.date) == .orderedAscending})
        return orderArray
    }

And this is the how I set the properties of my CoreDataClass:

@NSManaged public var commnt: String?
    @NSManaged public var date: NSDate?
    @NSManaged public var value: Int16
    @NSManaged public var take: Int16

Solution

  • result.date is an optional NSDate, so you can bridge it to an optional Date:

    result.date as Date?
    

    Then use optional binding to safely unwrap it. In your case that could be

    guard let date = result.date as Date? else {
        // date is nil, ignore this entry:
        continue
    }
    

    You might also want to replace

    let commnt = String(describing: result.commnt)
    

    with

    guard let commnt = result.commnt else {
        // commnt is nil, ignore this entry:
        continue
    }
    

    otherwise you'll get comment strings like Optional(My comment).

    (Rule of thumb: String(describing: ...) is almost never what you want, even if the compiler suggests it to make the code compile.)