首页 > 解决方案 > 使用数组中的所有值执行任务(Swift、Firebase)

问题描述

我的情况是我正在创建一个社交媒体应用程序,并且我有一系列用户正在关注的人。它看起来像这样:

let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]

因此,我想使用数组中的每个 userUid 执行一个函数来获取他们的帖子并将其显示到 collectionView 上。

为了提供更多上下文,函数看起来像这样(“userUid”是我需要与所有使用数组的 userUid 重复的元素):

databaseRef.child("posts").child(userUid).observeSingleEvent(of: .value) { (snapshot) in
// all of the code to get the posts information into another array to display on the collection view.

}

非常感谢!

标签: arraysswiftfirebasefirebase-realtime-database

解决方案


要对数组中的每个元素执行某些操作,您始终可以使用forEach(_:)。尝试:

let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]

for userID in followingArray {
    databaseRef.child("posts").child(userID).observeSingleEvent(of: .value) { (snapshot) in
        // all of the code to get the posts information into another array to display on the collection view.
    }
}

推荐阅读