0

I am using two arrays:

var facebookFriends: [FacebookFriend] = []

var friendsToInvite: [FacebookFriend]!

The first array contains all the Facebook friends and the second one contains objects FacebookFriend which have selected in a different ViewController.

Both of the arrays are instantiated correctly in the ViewController.

In the -tableView:cellForRowAtIndexPath delegate method I want to change the cell view if the Facebook friend from the facebookFriends array is contained in the friendsToInvite array.

In order to acheive that, I have tried the following:

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

But I get the following error:

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

Is there any other way to check if this object is contained in the array?

2
  • What kind of value stored in '[FacebookFriend]' ? Commented Jan 19, 2016 at 10:09
  • I have created my own class ` FacebookFriend ` and I use the following constructor in order to create an object: ` init(facebookId: String, facebookUsername: String, profilePicture: NSData) { self.facebookId = facebookId self.facebookUsername = facebookUsername self.profilePicture = profilePicture } ` Commented Jan 19, 2016 at 10:11

2 Answers 2

2

Your FacebookFriendclass must conform to Equatableprotocol in order to have the contains() method to work. This protocol allows the comparison of objects .

Let's do it with a simplified facebookFriendclass :

class facebookFriend {

    let name:String
    let lastName:String

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

}

You can conform to Equatable protocol quite easily :

extension facebookFriend: Equatable {}

    func ==(lhs: facebookFriend, rhs: facebookFriend) -> Bool {
        let areEqual = lhs.name == rhs.name &&
        lhs.lastName == rhs.lastName
        return areEqual
    }
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You can make a filter using

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.