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
The class we use to convert a string to a date in Swift is DateFormatter (or NSDateFormatter if you are using Objective-C).
Swift – Get Current Date Only To get only current date, containing day, month and year, use Date and DateFormatter . Date returns current point in time, while DateFormatter with specified dateFormat formats this Date value to required format, like in this case returning only date (day, month and year).
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.)
Just make implicit casting like:
let nsdate = NSDate()
let date = nsdate as Date
You can use a function or just an extension:
let nsDate = NSDate()
let date = Date(timeIntervalSinceReferenceDate: nsDate.timeIntervalSinceReferenceDate)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With