swift - CLLocationCoordinate2D 不符合预期的字典值类型 'AnyObject'

标签 swift casting core-location nsnotificationcenter

每当在 locationManager(_:didUpdateLocations:) 中检索到新位置数据时,我的单例位置管理器都会发布通知:

...
 NSNotificationCenter.defaultCenter().postNotificationName("LocationUpdate", object: self, userInfo: ["currentLocation": currentLocation,
                                                                                                      "currentLocationPoints": currentLocationPoints])`
...

通过上面的通知发布,我在 userInfo 部分收到以下错误:

Value of type 'CLLocationCoordinate2D! does not conform to expected dictionary value type 'AnyObject'`

因此我进行了以下类型转换:

userInfo: ["currentLocation": currentLocation as! AnyObject,
           "currentLocationPoints": currentLocationPoints as! AnyObject]

这次我在运行时遇到以下错误:

Could not cast value of type '__C.CLLocationCoordinate2D' (0xbb1f0) to 'Swift.AnyObject' (0x312d074).

为什么转换失败?我知道 AnyAnyObject 之间的区别 AnyObject 不能是枚举之类的,但是 CLLocationCoordinate2D 应该是适合类型转换。

最佳答案

CLLocationCoordinate2D 是一个 struct 并且不符合 AnyObject 协议(protocol)。因此它不能存储到字典中。

一个可能的解决方案是分别发布 latitudelongitudeDouble 值。

另一种解决方案是链接到 MapKit.framework 并使用 NSValue 的扩展(符合 AnyObject)

设置:

let value = NSValue(MKCoordinate: currentLocation)
dictionary["currentLocation"] = value

得到:

let value = dictionary["currentLocation"] as! NSValue
let currentLocation = value.MKCoordinateValue

关于swift - CLLocationCoordinate2D 不符合预期的字典值类型 'AnyObject',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34703737/

相关文章:

java - 摆脱丑陋的 Actor 阵容

ios - 无法通过GPS在ios8中获取经度和纬度

swift - uinavigationcontroller 的异常行为点击 UIButton 抛出异常

swift - 如何更改 UIAlertController 中按钮的字体

ios - “SDWebImageCompat.h”文件未找到错误

ios - xcode - 如何在没有 CoreLocation 的情况下找到你的当前位置

ios - CLLocationManager 的 AuthorizationStatus 在 iOS 14 上已弃用

ios - Swift Playground 力下一页

Java 泛型 : casting to ? (或使用任意 Foo<?> 的方法)

java - 重复类型转换