【问题标题】:Cannot subscript Dictionary with String不能用字符串下标字典
【发布时间】:2016-02-21 04:56:29
【问题描述】:

我编写了以下函数来访问 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)
}

但我无法访问密钥,因为我收到错误:

不能用“String”类型的索引为“Dictionary String,AnyObject> 类型的值下标

【问题讨论】:

    标签: swift nsdictionary


    【解决方案1】:

    您正在尝试将AnyObject 分配给标签的text 属性。我会去:

    func updateAddressLabel(notification: NSNotification) {
        if let userInfo = notification.userInfo as? Dictionary<String,AnyObject>, let geocodeLocation = userInfo["geocodeLocation"] as? String {
            infoLabelAddress.text = geocodeLocation
        }
    }
    

    【讨论】:

      【解决方案2】:

      userInfoDictionary&lt;String,AnyObject&gt;,要将值分配给特定类型,例如 String,您必须向下转换对象

      self.infoLabelAddress.text = userInfo["geocodeLocation"] as! String
      

      【讨论】:

        猜你喜欢
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-03
        相关资源
        最近更新 更多