【问题标题】:Reducing multiple arrays into one array in Swift and Firebase在 Swift 和 Firebase 中将多个数组缩减为一个数组
【发布时间】:2017-12-10 15:59:42
【问题描述】:

我正在寻找一个函数,允许我根据我当前的朋友列表拉出更多朋友的列表。我从提取我当前的朋友列表开始,对于每个朋友,我提取他们的朋友列表并将其附加到一个数组中。但是,我现在的输出类似于 ["friendId1","friendId2"]["friendId1","friendId2","friendId3","friendId4"] 我希望它只显示第二行 ["friendId1 ","friendId2","friendId3","friendId4"]

func fetchOtherFriends(completion: @escaping ([String]) -> Void) {


    let currentUser = Auth.auth().currentUser!.uid
    Database.database().reference().child("friends").child(currentUser).observeSingleEvent(of: .value, with: { (snapshot : DataSnapshot) in

        // Iterate through all the children:

        for child in snapshot.children.allObjects as! [DataSnapshot] {


            let value = child.value as? NSDictionary

            let userId = value?["userId"] as? String ?? ""


            Database.database().reference().child("friends").child(userId).observeSingleEvent(of: .value, with: { (snapshot : DataSnapshot) in

                // Iterate through all the children:

                for child1 in snapshot.children.allObjects as! [DataSnapshot] {


                    let value1 = child1.value as? NSDictionary

                    let userId1 = value1?["userId"] as? String ?? ""

                    self.otherfriendsArray.append(userId1)

                    completion(self.otherfriendsArray)

                }         
            })   
        }  
    })     
 }

【问题讨论】:

    标签: arrays swift firebase


    【解决方案1】:

    如果我正确理解您的问题,那么您可以使用 flatmap

    输入:

    let friendList = [["friend1","friend2"],["friend3","friend4"]]
    

    解决方案:

    let result = friendList.flatMap{ $0 }
    

    输出:

    ["friend1", "friend2", "friend3", "friend4"]
    

    【讨论】:

    • 很遗憾,friendList 目前没有设置为多维数组。很简单 ["friend1","friend2"] (下一行) ["friend1","friend2","friend3","friend4"] 因为他们正在循环访问多个当前朋友。如果有意义的话,不确定如何只使用第二行。
    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 2018-08-03
    • 2021-09-16
    • 2019-03-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2020-09-24
    相关资源
    最近更新 更多