gpt4 book ai didi

ios - 使用 Firebase 将来自多个循环的值存储到一个数组中。迅速

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:29:33 27 4
gpt4 key购买 nike

我一直在尝试找出如何获取用户数据数组并将其与其他用户数组列表进行比较以查看它是否与它们匹配。我看过答案 here这表明我应该构建我的数据,使其非规范化并因此具有重复项。这种方法有效,但我现在正在努力将这些数组存储到一个数组中,以便以后使用。

这是我的数据结构的一个例子:

{
“skills”: [
{
"name": "Walking"
},
{
"name": "Running",
"usersWithSkill": [
“user1”: true,
“user2”: true,
“user3”: true
]
},
{
"name": "Swimming",
"usersWithSkill": [
“user3”: true
]
},
{
"name": "Dancing",
"usersWithSkill": [
“user1”: true,
“user3”: true
]
}
],
"users": {
"user1": {
"firstName": "Amelia",
"skillsList": [
"1": true,
"3": true
]
},
"user2": {
"firstName": "Elena",
"skillsList": [
"1": true,
]
},
"user3": {
"firstName": "John",
"skillsList": [
"1": true,
"2": true,
"3": true
]
},
“user4”: {
"firstName": "Jack",
"interestsList": [
"1": true,
"3": true
]
}
}
}

我可以查询 Jack 的兴趣。然而,循环发生了两次,因此我很难附加一个数组来存储 Jack 正在寻找的用户的值。

我是这样查询技能的:

var newArray = [String]()

func fetchSkillKeys() {

// Loop through the array of interest keys
for key in self.arrayOfInterestKeys {
let interestRef = Database.database().reference(withPath: "skills/\(key)/usersSkill")
interestRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in
for child in snapshot.children {
guard let snapshot = child as? DataSnapshot else { continue }
self.newArray.append(snapshot.key)
}
print(self.newArray)
})
}
}

这是我的数组在控制台上打印时的样子:

[]
["0", "1", "2"]
["0", "1", "2", "0", "1", "2"]
["0", "1", "2", "0", "1", "2", "0", "1"]

当我期待这样的事情时:

["0", "1", "2", "0", "1"]

更新

根据下面的评论,arrayOfInterestKeys 是从 interestsList 中获取的键,我在查询我想观察的技能时将其用作引用,以下是我如何获取它们:

var arrayOfInterestKeys = [String]()

func fetchUserInterests() {

guard let uid = Auth.auth().currentUser?.uid else { return }
// Go to users interest list
let databaseRef = Database.database().reference(withPath: "users/\(uid)/interestsList")

// Observe the values
databaseRef.observeSingleEvent(of: DataEventType.value, with: { (snapshot) in

// Loop through the interests list
for child in snapshot.children {
guard let snapshot = child as? DataSnapshot else { continue }
// Populate an empty array
self.arrayOfInterestKeys.append(snapshot.key)
}
})
}

最佳答案

你有:

for child in snapshot.children {
guard let snapshot = child as? DataSnapshot else { continue }
self.newArray.append(snapshot.key)
}
print(self.newArray)

尝试:

for child in snapshot.children {
let child = child as? DataSnapshot
if let key = child?.key {
// Make sure the key is not in the array
if self.newArray.index(of: key) == nil {
self.newArray.append(key)
}
}
}

另外我想知道你如何/在哪里调用 fetchSkillKeys()

关于ios - 使用 Firebase 将来自多个循环的值存储到一个数组中。迅速,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48490027/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com