【问题标题】:Swift 3.0 notification transformable to array or array of dictionaries?Swift 3.0 通知可转换为数组或字典数组?
【发布时间】:2017-02-09 03:20:02
【问题描述】:

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

    %@ [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 示例可能会有所帮助。

【问题讨论】:

    标签: notifications swift3 hashable


    【解决方案1】:

    通知userInfo被解析为Dictionary<String, Any>[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]]()
    

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 1970-01-01
      • 2018-11-26
      • 2021-10-18
      • 2017-02-24
      • 1970-01-01
      • 1970-01-01
      • 2016-05-15
      • 2018-01-08
      相关资源
      最近更新 更多