每当在 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).
为什么转换失败?我知道 Any
和 AnyObject
之间的区别 AnyObject
不能是枚举之类的,但是 CLLocationCoordinate2D
应该是适合类型转换。
最佳答案
CLLocationCoordinate2D
是一个 struct
并且不符合 AnyObject
协议(protocol)。因此它不能存储到字典中。
一个可能的解决方案是分别发布 latitude
和 longitude
的 Double
值。
另一种解决方案是链接到 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/