Swift : '(NSObject, AnyObject)' does not have a member named 'subscript'

时间秒杀一切 提交于 2019-12-01 17:38:12

The shortest one is:

// Xcode 6.0.1
func handleRemoteNotifiation(userInfo: [NSObject : AnyObject]) {
    if let badge = [userInfo["aps"]?["badge"]][0] as? Int {
        self.updateAppIconBadgeNumber(badge)
    }
}

// Xcode 6.1
func handleRemoteNotifiation(userInfo: [NSObject : AnyObject]) {
    if let badge = userInfo["aps"]?["badge"] as? Int {
        self.updateAppIconBadgeNumber(badge)
    }
}

? between ["aps"] and ["badge"] is called "Optional Chaining". You need this because userInfo["aps"] can returns nil. And you don't have to cast it to [String : AnyObject] because every AnyObject has 'subscript' member.

And, Why we need [ ... ][0] in Xcode 6.0.1 is... I don't know :( .a bug, maybe.

You could use nil coleascing operator and make it short but you may loose readability. If have a single line version of the method like this,

func handleRemoteNotification(userInfo: [NSObject : AnyObject]) {
  if let badge = ((userInfo["aps"] as? [String: AnyObject]) ?? ([String: AnyObject]()))["badge"] as? Int{
      self.updateAppIconBadgeNumber(badge)
  }
}

You could typealias [String: AnyObject] and make it look little more readable.

typealias Dict = [String: AnyObject]
func handleRemoteNotifiation(userInfo: [NSObject : AnyObject]) {
    if let badge = ((userInfo["aps"] as? Dict) ?? Dict())["badge"] as? Int{
        self.updateAppIconBadgeNumber(badge)
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!