我从两个Firebase JSON树中提取数据。来自这些树的数据被下载到两个数组中。 “用户”和“活动”
用户数组是结构化的
▿ Shoota.Userdata #0
- userId: "NhZZGwJQCGe2OGaNTwGvpPuQKNA2"
- name: "Christian"
- city: "Oslo"
- country: "Norway"
- profileImage: "https://firebasestorage.googleapis.com/v0/b/shoota-179610.appspot.com/o/profile_image%2FA176B8AD-EF7D-4C8F-BA7C-06B538795E9D?alt=media&token=025d8d1a-b610-4525-a154-73300599d84c"
活动数组的结构是:
▿ Shoota.Activity #0
- _userId: "NhZZGwJQCGe2OGaNTwGvpPuQKNA2"
- _name: "Test"
- _type: "Pheasent"
- _weapon: "Browning 12 CAL"
- _kills: "12"
- _sightings: "100"
- _note: "Great day of hunting"
此数据用于填充UITableView。从“users”获取相应“profileImage”的最有效方法是什么,其中Activity._userId = users.userId?
答案 0 :(得分:0)
唯一的方法是迭代元素。但如果这是经常运行的话,最好让它为用户阵列扩展。上面的代码仅对用户数组进行扩展。
struct User{
var userId: String
var profileImage: URL
}
extension Array where Element == User {
func getImage(forId id: String) -> User?{
return self.first { (user) -> Bool in
user.userId == id
}
}
}
并使用它:user.getImage(forId: activity._userId)
或者,如果不想要任何扩展名,只需使用:
users.first { (user) -> Bool in
user.userId == activity._userId
}
答案 1 :(得分:0)
这就是我最终解决这个问题的方法。
let filteredUsers = userdataArray.filter {$0.userId == userId}
if filteredUsers.count > 0 {
let profileImageURL = filteredUsers.first!.profileImage
profileName = filteredUsers.first!.name
cell.profileImageView.kf.setImage(with: URL.init(string:profileImageURL))
} else {
cell.profileImageView.image = UIImage(named: "profile_image_placeholder")
}