ios - Swift 3 遍历嵌套字典?

标签 ios swift loops

好的,所以,快速的菜鸟警报:

如何在给定以下数组的情况下进行最简单的迭代(我不知道如何称呼此形状:数组、字典、对象...)?

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/

相关文章:

iphone - 如何在 iOS 中使用 OpenGL ES 2.0 绘制矩形?

ios - 如何在 iPhone SDK 中获取 facebook 相册的照片?

ios - 按月份对 NSDictionary 的值进行分组和求和,其中键为 NSDate

ios - AVAudioPlayer 正在播放加时 View 续。加载[ swift ]

ios - Swift 的 AVAudioEngine 类中的 detachNode 做了什么?

swift - Property Wrapper @Lazy 变量线程安全吗?

ios - 从底部向上布局 SwiftUI 列表单元格

python - 如何使用函数作为 while 循环条件?

javascript - 使用循环进行空白替换 javascript 的更有效解决方案

java - 让应用程序等待几秒钟 Java