无法使用类型为“NSKeyValueChangeKey”的索引下标“[NSObject:AnyObject]”类型的值

时间:2018-05-29 10:46:23

标签: ios swift google-maps

我在使用此代码时收到此错误。

错误:无法下标类型为'[NSObject:AnyObject]'的值,其索引类型为'NSKeyValueChangeKey'

func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutableRawPointer) {
    if !didFindMyLocation {
        let myLocation: CLLocation = change[NSKeyValueChangeNewKey] as CLLocation
        viewMap.camera = GMSCameraPosition.camera(withTarget: myLocation.coordinate, zoom: 10.0)
        viewMap.settings.myLocationButton = true

        didFindMyLocation = true
    }
}

1 个答案:

答案 0 :(得分:2)

这是observeValue(forKeyPath:of:change:context:)(Swift 4)的正确签名:

func observeValue(forKeyPath keyPath: String?, 
                of object: Any?, 
           change: [NSKeyValueChangeKey : Any]?, 
          context: UnsafeMutableRawPointer?)

无论语言版本如何,您的关键是将change: [NSObject : AnyObject]更改为change: [NSKeyValueChangeKey : Any]?