arrays - 检索字典值并将它们附加到数组 Swift

标签 arrays swift dictionary

我有这个字典:

["1hoxy7StFyU4QzQTwgDrwAoCZ": {
    address = "example2";
    date = "28-02-2017";
    location = "....";
    number = 1111;
    user = S4KaKn5Qz4bDDha57DMLcnaCHn21;
}"1hoxy7StFyU4QzQfrsqfsqfDZz": {
    address = "example2";
    date = "28-02-2017";
    location = "....";
    number = 222;
    user = S4KaKn5Qz4bDDha57DMLcnaCHn22;
}]

我想检索此 Dictionnary 的所有 user 值并将它们附加到 Array 中。 此 Dictionnary 使用 Firebase 数据库检索。

  if let dict = snapshot.value as? [String : AnyObject] {

                print(dict)

                self.asksList.append(dict["user"] as! String)

                print(self.asksList)

                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }

我该怎么做?预先感谢您的帮助!

最佳答案

你有嵌套的字典,所以你可以通过这种方式获得所有的user

if let dict = snapshot.value as? [String : [String:Any]] {
    for (_, value) in dict { 
        if let user = value["user"] as? String {
            self.asksList.append(user)
        }
    }       
    //Firebase completion block will called in main thread so directly reload the tableView
    self.tableView.reloadData()
}

或者您可以使用flatMap 而不是遍历for 循环

if let dict = snapshot.value as? [String : [String:Any]] {
    let array = dict.flatMap { $1["user"] as? String }
    self.asksList += array 
    //Firebase completion block will called in main thread so directly reload the tableView
    self.tableView.reloadData()
}

关于arrays - 检索字典值并将它们附加到数组 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42490332/

相关文章:

c# - $push 操作期间非文档嵌套数组的排序规范

swift - 如何在 iOS 8 中实现 iOS 9 的 UIUserNotificationActionBehavior.TextInput?

swift - ld : framework not found AFNetworking clang: error: linker command failed with exit code 1 (use -v to see invocation)

ios - 选项卡 View Controller 中嵌入了 protected View ?

c++ - 向 typedef 添加函数

R 整数键,值映射

java - 从数组中删除重复项。打印 HashMap 时出错

java - 比较字符串数组的数组列表

javascript - 在 React 中处理状态和对象数组

python - 如何根据内容从 numpy 数组中提取行?