将CLLocationDegrees更改为Double/NSNumber以保存在Core Data(Swift)中

Dar*_*ren 7 core-location swift

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

我只是想将CLLocationDegrees值保存到Core Data中.但我所做的一切都在起作用.

我开始时:

self.myLocation?.locationCurrentLat = self.fixedLocation?.coordinate.latitude
Run Code Online (Sandbox Code Playgroud)

但是不知道如何让CLLocationDegrees向Double或NSNumber投降(如果这是正确的话),我在Google上搜索的任何东西都无济于事!

关于很多事情,我显然仍然模糊不清.这肯定是其中之一.

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

提前致谢

Dun*_*n C 19

CLLocationDegrees 双倍的.你不应该做任何事情.

如果确实需要将其强制转换为double,请使用语法

Double(self.fixedLocation?.coordinate.latitude ?? 0)
Run Code Online (Sandbox Code Playgroud)

要转换为NSNumber,您可以使用

NSNumber(value: self.fixedLocation?.coordinate.latitude ?? 0)
Run Code Online (Sandbox Code Playgroud)

编辑:

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

let latitude: Double?
if let location = self.fixedLocation {
  latitude =     Double(location.coordinate.latitude)
} else {
  latitude = nil
}
Run Code Online (Sandbox Code Playgroud)

  • 要记住的关键是,一个可选项实际上是一个不同于它可选的数据类型.它实际上是一个包含该东西的枚举.这就是"解缠"的意思.打开可选项并取出存储在其中的对象.(PS Upvotes赞赏你找到有用的答案) (3认同)

Pri*_*est 5

以下是如何在Objective-C中转换为NSNumber;

[NSNumber numberWithDouble:newLocation.coordinate.longitude]
Run Code Online (Sandbox Code Playgroud)