2017-12-10 10 views
0

現在の友達のリストに基づいて、より多くの友人のリストを取得できるようにする関数を作成しようとしています。私は現在の友人のリストを引き出すことから始めています。そして、それらの友達のそれぞれについて、友人のリストを引っ張り、それを配列に追加します。しかし、私の出力は今、["friendId1"、 "friendId2"] ["friendId1"、 "friendId2"、 "friendId3"、 "friendId4"]のようなもので、2行目を表示したいと思う["friendId1 」、 "friendId2"、 "friendId3"、 "friendId4"]SwiftとFirebaseで複数の配列を1つの配列に減らす

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) 

       }   
      }) 
     } 
    })  
} 

答えて

0

私が正しくあなたの問題を理解した場合は、flatmapを使用することができます。

入力:

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

ソリューション:

let result = friendList.flatMap{ $0 } 

出力:

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

残念ながら、friendListがmultidimenとして設定されていません今すぐそれは複数の現在の友達をループしているので、それは単に["friend1"、 "friend2"](次の行)["friend1"、 "friend2"、 "friend3"、 "friend4"それが理にかなっていれば、2行目をどのように使うのかよく分かりません。 – user3410804