首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Swift和Firebase中将多个阵列合并为一个阵列

在Swift和Firebase中将多个阵列合并为一个阵列
EN

Stack Overflow用户
提问于 2017-12-10 23:59:43
回答 1查看 69关注 0票数 0

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

代码语言:javascript
运行
复制
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)

                }         
            })   
        }  
    })     
 }
EN

回答 1

Stack Overflow用户

发布于 2017-12-11 00:59:19

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

输入:

代码语言:javascript
运行
复制
let friendList = [["friend1","friend2"],["friend3","friend4"]]

解决方案:

代码语言:javascript
运行
复制
let result = friendList.flatMap{ $0 }

输出:

代码语言:javascript
运行
复制
["friend1", "friend2", "friend3", "friend4"]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47740605

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档