无法将“NSMutableDictionary”类型的值转换为预期的参数类型“[String: AnyObject]?”
Posted
技术标签:
【中文标题】无法将“NSMutableDictionary”类型的值转换为预期的参数类型“[String: AnyObject]?”【英文标题】:Cannot convert value of type 'NSMutableDictionary' to expected argument type '[String: AnyObject]?' 【发布时间】:2016-07-09 10:57:23 【问题描述】:我想跳过使用 Xcode 7.3.1 并转换我的代码,但我在这里遇到了一些问题,这就是我过去在 Swift 1.1 中使用它的方式,但我收到错误 - 无法转换值类型为“NSMutableDictionary”的参数类型为“[String: AnyObject]?”:
private func getPlacemark() -> CLPlacemark
var addressDict = NSMutableDictionary()
var formattedAddressArray = self.formattedAddress.componentsSeparatedByString(", ") as Array
let kSubAdministrativeArea = "SubAdministrativeArea"
let kSubLocality = "SubLocality"
let kState = "State"
let kStreet = "Street"
let kThoroughfare = "Thoroughfare"
let kFormattedAddressLines = "FormattedAddressLines"
let kSubThoroughfare = "SubThoroughfare"
let kPostCodeExtension = "PostCodeExtension"
let kCity = "City"
let kZIP = "ZIP"
let kCountry = "Country"
let kCountryCode = "CountryCode"
addressDict.setObject(self.subAdministrativeArea, forKey: kSubAdministrativeArea)
addressDict.setObject(self.subLocality, forKey: kSubLocality)
addressDict.setObject(self.administrativeAreaCode, forKey: kState)
addressDict.setObject(formattedAddressArray.first! as NSString, forKey: kStreet)
addressDict.setObject(self.thoroughfare, forKey: kThoroughfare)
addressDict.setObject(formattedAddressArray, forKey: kFormattedAddressLines)
addressDict.setObject(self.subThoroughfare, forKey: kSubThoroughfare)
addressDict.setObject("", forKey: kPostCodeExtension)
addressDict.setObject(self.locality, forKey: kCity)
addressDict.setObject(self.postalCode, forKey: kZIP)
addressDict.setObject(self.country, forKey: kCountry)
addressDict.setObject(self.ISOcountryCode, forKey: kCountryCode)
var lat = self.latitude.doubleValue
var lng = self.longitude.doubleValue
var coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lng)
var placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDict ) <-- getting error //Cannot convert value of type 'NSMutableDictionary' to expected argument type '[String: AnyObject]?'
return (placemark as CLPlacemark)
提前致谢!
【问题讨论】:
【参考方案1】:与不可变 NSDictionary
不同,可变 NSMutableDictionary
与 Swift Dictionary
无关,不能桥接或强制转换。
有一个简单的规则可以避免这些问题:
在 Swift 中,尽可能使用 Swift 原生集合类型。
var addressDict = [String:AnyObject]()
...
addressDict[kSubAdministrativeArea] = self.subAdministrativeArea
...
【讨论】:
以上是关于无法将“NSMutableDictionary”类型的值转换为预期的参数类型“[String: AnyObject]?”的主要内容,如果未能解决你的问题,请参考以下文章
无法将“Swift._SwiftDeferredNSDictionary<Swift.String, Swift.String>”类型的值转换为“NSMutableDictionary”
类别 NSMutableDictionary/NSDictionary 应该返回 NSMutableDictionary/NSDictionary 取决于调用者类
在 NSMutableDictionary 中设置 NSURLSessionDownloadTask