Convert NSDate to Date

This may be a stupid question, but I cannot find the information. I use CoreData in my application and I save an array of structures. The problem is that when I retrieve and try to restore it in a 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 to use it as Date, but it forces me to force downcast, and I'm not sure how safe it is. 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 get 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 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
+5
source share
3 answers

result.date NSDate, Date:

result.date as Date?

. ,

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

let commnt = String(describing: result.commnt)

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

, Optional(My comment).

( : String(describing: ...) , , .)

+6

, :

let nsdate = NSDate() 
let date = nsdate as Date
+1

You can use a function or just an extension:

let nsDate = NSDate() 
let date = Date(timeIntervalSinceReferenceDate: nsDate.timeIntervalSinceReferenceDate)
0
source

Source: https://habr.com/ru/post/1684052/


All Articles