将 CLLocationDegrees 更改为 Double/NSNumber 以保存在核心数据中 (Swift)

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

在尝试将我所有的 objective C 代码更改为 Swift(这本身就是一个非常陡峭的学习曲线)时,我遇到了一个问题。

我只是想将 CLLocationDegrees 值保存到核心数据中。但是我所做的一切都没有用。

我开始于:

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

但不知道如何将 CLLocationDegrees 向下转换(如果这是正确的)为 Double 或 NSNumber,我在 Google 上搜索的任何内容都没有帮助!

我对很多事情显然还是一头雾水。这当然是其中之一。

我可能做错了什么……或需要做什么?

提前致谢

CLLocationDegrees 的两倍。你不需要做任何事情。

如果确实需要将其转换为双精度数,请使用语法

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

但这并不需要,因为 CLLocationDegrees 是 double 的类型别名。

要转换为 NSNumber,您需要使用

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

编辑:

我编辑了上面的代码,如果 self.fixedLocation 为 nil,则使用 "nil coalescing operator" 给出值 0。如果 fixedLocation 为 nil,则将 return 设为包含 nil 的可选 Int 会更安全:

let latitude: Double?
if let location = self.fixedLocation {
  latitude =     Double(location.coordinate.latitude)
} else {
  latitude = nil
}

下面是如何在 Objective-C;

中转换为 NSNumber
[NSNumber numberWithDouble:newLocation.coordinate.longitude]