10

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

Darren
  • 1,682
  • 1
  • 15
  • 33

2 Answers2

25

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
}
Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • Thanks so much for this. Turns out my optionals were all over the place too. I really do need to go back and keep learning what these optionals mean as it's throwing me left, right and centre. – Darren May 13 '15 at 11:38
  • 3
    The key thing to remember is that an optional is actually a different data type than the thing it's an optional for. It's actually an enum that contains the thing. That's what "unwrapping" means. Opening up the optional and taking out the object stored inside. (P.S. Upvotes appreciated for answers you find helpful) – Duncan C May 13 '15 at 12:44
  • `CLLocationDegrees` (the type of `latitude`) is a type alias of `Double`. The initializer is redundant. – vadian Feb 19 '18 at 14:32
  • As I said, "CLLocationDegrees **is** a double". Does Swift even have casting between scalar types, or are you always using an initializer that takes a different scalar type as a parameter? – Duncan C Feb 20 '18 at 02:42
5

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

[NSNumber numberWithDouble:newLocation.coordinate.longitude]
Priest
  • 242
  • 4
  • 11
  • 1
    One thing I prefer about C/C++/Objective-C is it's handling of different numeric types. It will "auto-promote" a value to a different numeric type. In Swift you have to cast *EVERYTHING!* – Duncan C Nov 02 '17 at 14:43
  • Yessir, gotta maintain that type-safety! – Priest Nov 02 '17 at 19:21