好的,所以,快速的菜鸟警报:
如何在给定以下数组的情况下进行最简单的迭代(我不知道如何称呼此形状:数组、字典、对象...)?
func showNotification(_ sender: [AnyHashable: Any]) { ... }
sender["actions"]:
Optional([{"text":"Confirm","type":"response"},{"text":"Decline","type":"response"},{"link":"https://www.stackoverflow.com","text":"Website","type":"info"}])
尝试:
if let result = sender["actions"] {
print("YES \(result)")
for action in result as! [String] {
print(action)
}
}
上面的打印
:
YES [{"text":"Confirm","type":"response"},{"text":"Decline","type":"response"},{"link":"https:\/\/www.stackoverflow.com","text":"Website","type":"info"}]
...但是,返回以下错误:
无法将类型“__NSCFString”(0x1a7c28d50)的值转换为“NSArray”(0x1a7c297c8)
这里的最终目标是简单地单独执行每个操作,即:
{"text":"Confirm","type":"response"}
{"text":"Decline","type":"response"
等...
Swift 有 map
函数吗……仅供引用,我来自 Java 和 JavaScript 世界……swiftyjson
对于一个循环来说似乎有点重。
谢谢,一如既往地感谢任何帮助和指导!
编辑:
这是通过传递给函数 sender
的参数打印的:
sender: [AnyHashable("title"): title!, AnyHashable("message"): message, AnyHashable("message_id"): 0:1503511875428318%03300c3203300c32, AnyHashable("id"): 1497708240713, AnyHashable("actions"): [{"text":"Confirm","type":"response"},{"text":"Decline","type":"response"},{"link":"https:\/\/www.notifyd.com","text":"Website","type":"info"}], AnyHashable("aps"): {
"content-available" = 1;
}]
最佳答案
您想解码 JSON 字符串,然后转换为字典数组:
if
// cast sender["actions"] to String
let actionsString = sender["actions"] as? String,
// decode data of string and then cast to Array<Dictionary<String, String>>
let actionsStringData = actionsString.data(using: .utf8),
let result = try JSONSerialization.jsonObject(with: actionsStringData, options: []) as? [[String : String]]
{
print("YES \(result)")
for action in result {
print(action)
}
}
关于ios - Swift 3 遍历嵌套字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45845528/