Swift 检查一个对象数组是否包含另一个数组的对象

Swift check if an array of objects contains an object of another array

我正在使用两个数组:

var facebookFriends: [FacebookFriend] = []

var friendsToInvite: [FacebookFriend]!

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

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

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

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

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

但是我得到以下错误:

Cannot subscript a value of type '[FacebookFriend]'.

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

您的 FacebookFriendclass 必须符合 Equatable 协议才能使 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
    }
}

您可以使用

制作过滤器
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
}