不能用字符串下标字典
Cannot subscript Dictionary with String
我编写了以下函数来访问 userInfo 字典:
func updateAddressLabel(notification: NSNotification) {
let userInfo:Dictionary<String,AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
self.infoLabelAddress.text = userInfo["geocodeLocation"]
}
func updateDispatchInformation(notification: NSNotification) {
let userInfo:Dictionary<String,AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
let streetName = userInfo["streetName"]
let incidentLatitude = userInfo["latitude"]
let incidentLongitude = userInfo["longitude"]
// Set Dispatch Info Label
self.infoLabelTitle.text = "Notruf"
self.infoLabelAddress.text = streetName
self.createIncidentAnnotation(incidentLatitude, longitude: incidentLongitude)
}
但是我无法访问密钥,因为我收到错误消息:
Cannot subscript a value of type 'Dictionary String,AnyObject> with an index of type 'String'
userInfo
是 Dictionary<String,AnyObject>
,要将值分配给特定类型,例如 String
,您必须向下转换对象,例如
self.infoLabelAddress.text = userInfo["geocodeLocation"] as! String
您正在尝试将 AnyObject
分配给标签的 text
属性。我会去:
func updateAddressLabel(notification: NSNotification) {
if let userInfo = notification.userInfo as? Dictionary<String,AnyObject>, let geocodeLocation = userInfo["geocodeLocation"] as? String {
infoLabelAddress.text = geocodeLocation
}
}
我编写了以下函数来访问 userInfo 字典:
func updateAddressLabel(notification: NSNotification) {
let userInfo:Dictionary<String,AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
self.infoLabelAddress.text = userInfo["geocodeLocation"]
}
func updateDispatchInformation(notification: NSNotification) {
let userInfo:Dictionary<String,AnyObject> = notification.userInfo as! Dictionary<String, AnyObject>
let streetName = userInfo["streetName"]
let incidentLatitude = userInfo["latitude"]
let incidentLongitude = userInfo["longitude"]
// Set Dispatch Info Label
self.infoLabelTitle.text = "Notruf"
self.infoLabelAddress.text = streetName
self.createIncidentAnnotation(incidentLatitude, longitude: incidentLongitude)
}
但是我无法访问密钥,因为我收到错误消息:
Cannot subscript a value of type 'Dictionary String,AnyObject> with an index of type 'String'
userInfo
是 Dictionary<String,AnyObject>
,要将值分配给特定类型,例如 String
,您必须向下转换对象,例如
self.infoLabelAddress.text = userInfo["geocodeLocation"] as! String
您正在尝试将 AnyObject
分配给标签的 text
属性。我会去:
func updateAddressLabel(notification: NSNotification) {
if let userInfo = notification.userInfo as? Dictionary<String,AnyObject>, let geocodeLocation = userInfo["geocodeLocation"] as? String {
infoLabelAddress.text = geocodeLocation
}
}