Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Self-Destructing Message iPhone App Relating Users in Parse.com Removing Friends by Tapping on a Table View Cell

Roderick Kar
Roderick Kar
8,456 Points

how to remove a friend from the array of friends using Swift? removeObject method seems not available at Swift

removeObject seems not available to array in Swift. I do find removeAtIndex which led me to indexOfAccessibilityElement. but I am not sure what to use as the accessibility element that is required as the parameter. I have tried using both self.friends! and friend and then tried to print out self.friends! to see if the friend had been removed from the array - both result in fatal error: Array index out of range.

Any help would be much appreciated. Thanks.

    if isFriend(user){
        // remove checkmark
        cell?.accessoryType = UITableViewCellAccessoryType.None

        // remove from the array of friends
        for friend in self.friends! {
            if friend.objectId == user.objectId {

                self.friends!.removeAtIndex(friend.indexOfAccessibilityElement(self.friends!))
            }
            println(self.friends!)
        }

        // remove from the backend

    } else { ...

1 Answer

Stone Preston
Stone Preston
42,016 Points

im not really sure what indexOfAccessibilty element does but thats not what you want to use. you just need to use find() in conjunction with removeAtIndex. you pass in the array you want to serach through along with the item you are looking for to the find function. that will give you the index. keep in mind that find returns an optional so you will need to unwrap it, then you just call the removeAtIndexFunction on your array and pass in the index.

if friend.objectId == user.objectId {
    if let foundIndex = find(self.friends!, friend) {

         //remove the item at the found index
         self.friends!.removeAtIndex(foundIndex)

    }

 }
Roderick Kar
Roderick Kar
8,456 Points

Hello Stone again!

You are my hero! Thanks again for posting a solution promptly. By the way, self.friends in the if condition does need to be unwrapped or else error.

Thank you again.

Regards,

Rod

Stone Preston
Stone Preston
42,016 Points

woops, edited my answer and added the ! to unwrap it. glad you got it working