swift - Convert NSDate to Date -


this might stupid question, can´t find information. i'm using coredata in app, , save array of structs. problem when fetch , try restore struct array, have problem date variable; can't find way convert nsdate date, try using as date, makes me force downcast , i'm not sure if it's safe. correct? or there way?

this struc:

struct mydata {         var value = int()         var date = date()         var take = int()         var commnt = string()     } 

this how i'm fetchin data:

func fetchrequestinfo() -> [mydata] {          let fetchrequest: nsfetchrequest<glucoseevents> = glucoseevents.fetchrequest()          {             let searchresults = try databasecontroller.getcontext().fetch(fetchrequest)              result in searchresults [glucoseevents] {                let value = int(result.value)                let date = result.date 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 how set properties of coredataclass:

@nsmanaged public var commnt: string?     @nsmanaged public var date: nsdate?     @nsmanaged public var value: int16     @nsmanaged public var take: int16 

result.date optional nsdate, can bridge optional date:

result.date date? 

then use optional binding safely unwrap it. in case be

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

you might want replace

let commnt = string(describing: result.commnt) 

with

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

otherwise you'll comment strings optional(my comment).

(rule of thumb: string(describing: ...) never want, if compiler suggests make code compile.)


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -