【问题标题】:Swift check if an array of objects contains an object of another arraySwift 检查对象数组是否包含另一个数组的对象
【发布时间】:2016-04-24 18:01:50
【问题描述】:

我正在使用两个数组:

var facebookFriends: [FacebookFriend] = []

var friendsToInvite: [FacebookFriend]!

第一个数组包含所有 Facebook 好友,第二个数组包含对象 FacebookFriend,它们已在不同的 ViewController 中选择。

两个数组都在 ViewController 中正确实例化。

-tableView:cellForRowAtIndexPath 委托方法中,如果facebookFriends 数组中的Facebook 好友包含在friendsToInvite 数组中,我想更改单元格视图。

为了实现这一点,我尝试了以下方法:

if(friendsToInvite.contains(facebookFriends[indexPath.row])) {
    // Code to change the view of the cell
 }

但我收到以下错误:

不能为“[FacebookFriend]”类型的值下标。

有没有其他方法可以检查这个对象是否包含在数组中?

【问题讨论】:

  • “[FacebookFriend]”中存储了什么样的值?
  • 我创建了自己的类 `FacebookFriend`,并使用以下构造函数来创建对象:`init(facebookId: String, facebookUsername: String, profilePicture: NSData) { self.facebookId = facebookId self.facebookUsername = facebookUsername self.profilePicture = profilePicture } `

标签: ios arrays swift2 contains equality


【解决方案1】:

您的FacebookFriendclass 必须符合Equatableprotocol 才能使contains() 方法起作用。这个protocol 允许比较对象。

让我们用一个简化的facebookFriendclass 来做:

class facebookFriend {

    let name:String
    let lastName:String

    init(name:String, lastName:String) {
        self.name = name
        self.lastName = lastName
    }

}

你可以很容易地遵守Equatable 协议:

extension facebookFriend: Equatable {}

    func ==(lhs: facebookFriend, rhs: facebookFriend) -> Bool {
        let areEqual = lhs.name == rhs.name &&
        lhs.lastName == rhs.lastName
        return areEqual
    }
}

【讨论】:

    【解决方案2】:

    你可以使用过滤器

    let friend:FacebookFriend = facebookFriends[indexPath.row]
    var filteredArray = friendsToInvite.filter( { (inviteFriend: FacebookFriend) -> Bool in
            return inviteFriend.userID == friend.userID
        });
    
    if(count(filteredFriend) > 0){
      // friend exist
    }
    else{
      // friend does not exist
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-29
      • 2023-04-05
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      相关资源
      最近更新 更多