Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change CLLocationDegrees into a Double/NSNumber to save in Core Data (Swift)

In trying to change all my objective C code into Swift (which is a pretty steep learning curve in itself), I've hit a problem.

I'm simply trying to save a CLLocationDegrees value into Core Data. But nothing I do is working.

I started with:

self.myLocation?.locationCurrentLat = self.fixedLocation?.coordinate.latitude

But have no idea how to get the CLLocationDegrees to downcast (if that's the right thing) to a Double or NSNumber and nothing I can search on Google is helping!

I'm still obviously foggy about lots of things. This is certainly one of them.

What might I be doing wrong ... or need to do?

Thanks in advance

like image 826
Darren Avatar asked May 13 '15 10:05

Darren


2 Answers

CLLocationDegrees is a double. You shouldn't need to do anything.

If you do need to cast it to a double, use the syntax

Double(self.fixedLocation?.coordinate.latitude ?? 0)

But that should not be needed because CLLocationDegrees IS a type alias for a double.

To convert to an NSNumber, you'd use

NSNumber(value: self.fixedLocation?.coordinate.latitude ?? 0)

Edit:

I edited the code above to use the "nil coalescing operator" to give the value 0 if self.fixedLocation is nil. It would be safer to make it return an optional Int that contains a nil if the fixedLocation is nil:

let latitude: Double?
if let location = self.fixedLocation {
  latitude =     Double(location.coordinate.latitude)
} else {
  latitude = nil
}
like image 65
Duncan C Avatar answered Nov 19 '22 23:11

Duncan C


Here's how to convert to NSNumber in Objective-C;

[NSNumber numberWithDouble:newLocation.coordinate.longitude]
like image 33
Priest Avatar answered Nov 19 '22 23:11

Priest