0

将此数据作为通知返回,并希望将其读入可用的变量类型。我让他们所有人都工作,但奖励和应用程序

    %@ [AnyHashable("description"): Open 10 common chests.,     AnyHashable("icon"):     localhost:8000//media/achievements/Common%20Chest%20Go-    Getter/bomb.jpg, AnyHashable("name"): Common Chest Go-Getter,     AnyHashable("gcm.message_id"):1486597426811663%bf6da727bf.   6da727, AnyHashable("rewards"): {"Battle helm":1,"Gems":1000}, AnyHashable("aps"): {
    alert = "Achievement Completed";
}]

那么如何将其转换为可用变量呢?

    AnyHashable("rewards"): {"Battle helm":1,"Gems":1000},     AnyHashable("aps"): {
    alert = "Achievement Completed";
}

返回的项目称为 userInfo 所以就像...

let rewards = userInfo["rewards"] as! [String:Int] 

不起作用,对此的任何帮助将不胜感激!我再次使用 swift 3.0,所以 swift 3.0 示例可能会有所帮助。

4

1 回答 1

1

通知userInfo被解析为Dictionary<String, Any>or[String: Any]

let userInfo: [String: Any] = [
    "description": "Open 10 common chests.",
    "icon": "localhost:8000//media/achievements/Common%20Chest%20Go-    Getter/bomb.jpg",
    "name": "Common Chest Go-Getter",
    "gcm.message_id": "1486597426811663%bf6da727bf.   6da727",

    "rewards": [
      "Battle helm": 1,
      "Gems":1000
    ],
    "aps": [
      "alert": "Achievement Completed"
    ]
]

if let rewards = userInfo["rewards"] as? [String: Any] {

  if let battle = rewards["Battle helm"] as? Int {
    print(battle) // 1
  }

  if let gems = rewards["Gems"] as? Int {
    print(gems) // 1000
  }

}

if let aps = userInfo["aps"] as? [String: Any] {

  if let alert = aps["alert"] as? String {
    print(alert) // Achievement Completed
  }

}

看起来你对此感到困惑:

let arrayOfStrings = [String]()
let dictionary = [String: Any]()

let arrayOfDictionaries = [[String:Any]]()
于 2017-02-09T17:48:31.200 回答