In my application I added one object in array when select cell and unselect and remove object when re-select cell. I used that code but give me error.
extens
In Swift 3 and 4
var array = ["a", "b", "c", "d", "e", "f"]
for (index, element) in array.enumerated().reversed() {
array.remove(at: index)
}
From Swift 4.2 you can use more advanced approach(faster and memory efficient)
array.removeAll(where: { $0 == "c" })
instead of
array = array.filter { !$0.hasPrefix("c") }
Read more here
This is official answer to find index of specific object, then you can easily remove any object using that index :
var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
// students[i] = "Max"
students.remove(at: i)
}
print(students)
// Prints ["Ben", "Ivy", "Jordell"]
Here is the link: https://developer.apple.com/documentation/swift/array/2994720-firstindex
The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:
if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
array.remove(at: index)
}
Swift 4
var students = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
if let index = students.firstIndex(where: { $0.hasPrefix("A") }) {
students.remove(at: index)
}
for var index = self.indexOfObject(object); index != NSNotFound; index = self.indexOfObject(object)
is for loop in C-style and has been removed
Change your code to something like this to remove all similar object if it have looped:
let indexes = arrContacts.enumerated().filter { $0.element == contacts[indexPath.row] }.map{ $0.offset }
for index in indexes.reversed() {
arrContacts.remove(at: index)
}
var a = ["one", "two", "three", "four", "five"]
// Remove/filter item with value 'three'
a = a.filter { $0 != "three" }