Swift:两个数组 - 使用一个值从第二个数组中获取相应的值

Posted

技术标签:

【中文标题】Swift:两个数组 - 使用一个值从第二个数组中获取相应的值【英文标题】:Swift: Two arrays - using value in one to get corresponding value from a second array 【发布时间】:2017-11-05 19:50:14 【问题描述】:

我正在从两个 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。从 Activity._userId = users.userId 的“用户”获取相应的“profileImage”最有效的方法是什么?

【问题讨论】:

看看这个:filtering array in swift 看到userId了吗?将其用作包含您的数据的结构字典中的键。 @Paulw11:你能详细说明一下吗? 加载 Shoota.Userdata 数组时,不要将数据放入数组中,将其放入键为 userId 的字典中。然后,当您读取第二个数组时,您只需使用 userId 值访问字典即可轻松获取用户数据 【参考方案1】:

唯一的方法是迭代元素。但如果这是频繁操作,最好将其扩展为用户数组。以上代码仅对用户数组进行扩展。

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
            

【讨论】:

或者将用户数据放入字典而不是数组 @Максуд:我喜欢扩展的想法。您会将其存储在单独的扩展 swift 文件中吗? @Chris_1983_Norway,可能是。但在这种情况下,我认为最好将其存储在您描述用户的文件中 @Chris_1983_Norway 如果答案适合您,请设置正确的答案【参考方案2】:

这就是我最终解决问题的方法。

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

【讨论】:

以上是关于Swift:两个数组 - 使用一个值从第二个数组中获取相应的值的主要内容,如果未能解决你的问题,请参考以下文章

从第二个数组中过滤匹配值的对象数组

如果找到第一个数组中的特定键,则在第二个数组中查找值

交错两个 numpy 索引数组,每个数组中的一项

Swift 3 数组 - 在其他数组的帮助下删除多个元素

Swift 5. 从第二个表格视图单元格(第二个 indexpath.row )显示数组

如何使用 extern NSString 将字符串值从第一个视图移动到第二个视图控制器