我在下面的代码片段中遇到错误。每次我尝试构建它时,编译器都会提示:
Cannot subscript a value of type '[NSObject : AnyObject]' with an index of type 'String'
这是代码,尽显其魅力:
import Foundation
import MapKit
enum LocationKey: String {
case Latitude = "lat"
case Longitude = "long"
case Title = "title"
}
extension MKPointAnnotation {
var propertyState: [NSObject: AnyObject] {
get {
return [ LocationKey.Longitude.rawValue as NSObject: NSNumber(value: coordinate.latitude),
LocationKey.Longitude.rawValue as NSObject: NSNumber(value: coordinate.longitude),
LocationKey.Title.rawValue as NSObject: title as AnyObject]
}
set {
let lat = (newValue[LocationKey.Latitude.rawValue] as NSNumber).doubleValue
let long = (newValue[LocationKey.Longitude.rawValue] as NSNumber).doubleValue
coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
title = newValue[LocationKey.Title.rawValue] as NSString
}
}
}
我真正遇到问题的代码行是:
let lat = (newValue[LocationKey.Latitude.rawValue] as NSNumber).doubleValue
let long = (newValue[LocationKey.Longitude.rawValue] as NSNumber).doubleValue
title = newValue[LocationKey.Title.rawValue] as NSString
非常感谢!
最佳答案
你的代码太复杂了。所有值都是值类型,因此将字典声明为 [String:Any]
– 顺便解决了错误 – 并摆脱了所有丑陋的类型转换为 NSNumber
和 任何对象
。
import Foundation
import MapKit
enum LocationKey: String {
case latitude = "lat"
case longitude = "long"
case title = "title"
}
extension MKPointAnnotation {
var propertyState: [String: Any] {
get {
return [ LocationKey.latitude.rawValue: coordinate.latitude,
LocationKey.longitude.rawValue: coordinate.longitude,
LocationKey.title.rawValue: title ?? ""]
}
set {
guard let lat = newValue[LocationKey.latitude.rawValue] as? CLLocationDegrees,
let long = newValue[LocationKey.longitude.rawValue] as? CLLocationDegrees else { return }
coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
title = newValue[LocationKey.title.rawValue] as? String
}
}
}
您甚至可以使用枚举作为键
extension MKPointAnnotation {
var propertyState: [LocationKey: Any] {
get {
return [ .latitude: coordinate.latitude,
.longitude: coordinate.longitude,
.title: title ?? ""]
}
set {
guard let lat = newValue[.latitude] as? CLLocationDegrees,
let long = newValue[.longitude] as? CLLocationDegrees else { return }
coordinate = CLLocationCoordinate2D(latitude: lat, longitude: long)
title = newValue[.title] as? String
}
}
}
注意:您的 getter 使用 LocationKey.Longitude
两次,这将导致编译器错误。
关于ios - 无法使用 '[NSObject : AnyObject]' 类型的索引为 'String' 类型的值添加下标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50141190/