0

I'm pulling out data from two Firebase JSON trees. The data from these trees are downloaded into two arrays. "users" and "activities"

the user array is structured

  ▿ 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"

the activity array is structured:

▿ Shoota.Activity #0
  - _userId: "NhZZGwJQCGe2OGaNTwGvpPuQKNA2"
  - _name: "Test"
  - _type: "Pheasent"
  - _weapon: "Browning 12 CAL"
  - _kills: "12"
  - _sightings: "100"
  - _note: "Great day of hunting"

This data is used to populate a UITableView. What is the most efficient way to get the corresponding "profileImage" from "users" where Activity._userId = users.userId?

  • check this out: [filtering array in swift](https://stackoverflow.com/questions/31824810/filtering-array-in-swift) – zombie Nov 05 '17 at 19:56
  • See that `userId`? use that as a key in a dictionary of structs that contains your data. – Paulw11 Nov 05 '17 at 19:59
  • @Paulw11: Can you elaborate a bit more? – Chris_1983_Norway Nov 05 '17 at 20:11
  • When you load the Shoota.Userdata array, don’t put that data into an array, put it in a dictionary where the key is the userId. Then when you are reading your second array you can easily get the user data simply by accessing the dictionary using the userId value – Paulw11 Nov 05 '17 at 20:17

2 Answers2

0

The only way is iterating over elements. But if this is frequent operation, its better to make it extansion for Array of Users. The above code makes extension only for Arrays of Users.

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
            }
    }
}

and use it: user.getImage(forId: activity._userId)

or, if don't want any extensions, just use:

users.first { (user) -> Bool in
            user.userId == activity._userId
            }
0

This is how I finally solved the issue.

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")
    }