How to Remove an Element of a Given Value from an Array in Swift

How to remove an element of a given value from an array in Swift

A filter:

 let farray = arr.filter {$0 != "b"} 

How to remove an element from an array in Swift

The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2) //["cats", "dogs", "moose"]

A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:

let pets = animals.filter { $0 != "chimps" }

Swift: Better way to remove a specific Object from an array?

Use firstIndex(where:) (previously called index(where:) in Swift 4.1 and earlier) to search the array for your object using the predicate { $0 === objectToRemove }, then call remove(at:) on the array to remove it:

if let idx = objectArray.firstIndex(where: { $0 === objectToRemove }) {
objectArray.remove(at: idx)
}

This allows you to search for your object whether it is Equatable or not.

How to remove an element from array of object on swift based on id?

loop through all the indexes of the array and check if the id you want to delete matches, if yes it will filter out and you can remove that index :-)

let idToDelete = 10
if let index = arrStudents.index(where: {$0.id == idToDelete}) {
array.remove(at: index)
}

if you want to remove multiple value in single iteration you should start the loop from last index to first index, so it will not crash (out of bound error )

var idsToDelete = [10, 20]
for id in idsToDelete {
for (i,str) in arrStudents.enumerated().reversed()
{
if str.id == id
{
arrStudents.remove(at: i)
}
}
}

Swift: Array - removing elements when condition is met

If this code snippet is really what you need to do (as @Joakim says, there may be other options), you need to make sure that indices remain valid after deleting objects.

One easy way to achieve this is by going through the array backwards, from end to start, by simply adding a .reversed():

for index in (0..<features.count).reversed() { ... }

That said, if you can move the deletion of all items where remains == 0 to a later pass, then it is as simple as

features.removeAll { $0.remains == 0 }

Removing object from array in Swift 3

The Swift equivalent to NSMutableArray's removeObject is:

var array = ["alpha", "beta", "gamma"]

if let index = array.firstIndex(of: "beta") {
array.remove(at: index)
}

if the objects are unique. There is no need at all to cast to NSArray and use indexOfObject:

The API index(of: also works but this causes an unnecessary implicit bridge cast to NSArray.

Of course you can write an extension of RangeReplaceableCollection to emulate the function. But due to value semantics you cannot name it removeObject.

extension RangeReplaceableCollection where Element : Equatable {
@discardableResult
mutating func remove(_ element : Element) -> Element?
{
if let index = firstIndex(of: element) {
return remove(at: index)
}
return nil
}
}

Like remove(at: it returns the removed item or nil if the array doesn't contain the item.


If there are multiple occurrences of the same object use filter. However in cases like data source arrays where an index is associated with a particular object firstIndex(of is preferable because it's faster than filter.

Update:

In Swift 4.2+ you can remove one or multiple occurrences of beta with removeAll(where:):

array.removeAll{$0 == "beta"}

Remove specific array element by cell text string value [swift 4]

You code is too complicated. As you are using a class as data source the extra arrays are redundant.

  • Remove checkedItems and uncheckedItems

    var checkedItems: [ListItem] {
    return dataHolder.filter { return $0.isChecked }
    }
    var uncheckedItems: [ListItem] {
    return dataHolder.filter { return !$0.isChecked }
    }

  • In cellForRow set the checkmark according to isChecked and reuse cells!

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 18.0) // better set this in Interface Builder
    let data = dataHolder[indexPath.row]
    cell.textLabel?.text = data.title
    cell.accessoryType = data.isChecked ? .checkmark : .none
    return cell
    }
  • in didSelectRowAt toggle isChecked in the model and update only the particular row

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    dataHolder[indexPath.row].isChecked.toggle()
    tableView.reloadRows(at: [indexPath], with: .none)
    tableView.deselectRow(at: indexPath, animated: true)
    saveDefaults()
    }
  • In tableView:commit:forRowAt: delete the row at the given indexPath

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
    dataHolder.remove(at: indexPath.row)
    myTableView.deleteRows(at: [indexPath], with: .fade)
    saveDefaults()
    }
    }
  • And you cannot save an array of a custom class to UserDefaults. I recommend to use a struct and Codable

    struct ListItem : Codable {
    var title: String
    var isChecked: Bool
    }

    func loadDefaults()
    {
    guard let data = UserDefaults.standard.data(forKey: "dataHolder") else {
    self.dataHolder = []
    return
    }
    do {
    self.dataHolder = try JSONDecoder().decode([ListItem].self, for: data)
    } catch {
    print(error)
    self.dataHolder = []
    }
    }

    func saveDefaults()
    {
    do {
    let data = try JSONEncoder().encode(self.dataHolder)
    UserDefaults.standard.set(data, forKey: "dataHolder")
    } catch {
    print(error)
    }
    }

How to remove all the element which equal to certain value in an array swift 4?

Use filter:

func removeId(id: Int) {
myItem = myItem.filter { $0.id != id }
}

Remove Specific Array Element, Equal to String - Swift

You can use filter() to filter your array as follow

var strings = ["Hello","Playground","World"]

strings = strings.filter { $0 != "Hello" }

print(strings) // "["Playground", "World"]\n"

edit/update:

Xcode 10 • Swift 4.2 or later

You can use the new RangeReplaceableCollection mutating method called removeAll(where:)

var strings = ["Hello","Playground","World"]

strings.removeAll { $0 == "Hello" }

print(strings) // "["Playground", "World"]\n"

If you need to remove only the first occurrence of an element we ca implement a custom remove method on RangeReplaceableCollection constraining the elements to Equatable:

extension RangeReplaceableCollection where Element: Equatable {
@discardableResult
mutating func removeFirst(_ element: Element) -> Element? {
guard let index = firstIndex(of: element) else { return nil }
return remove(at: index)
}
}

Or using a predicate for non Equatable elements:

extension RangeReplaceableCollection {
@discardableResult
mutating func removeFirst(where predicate: @escaping (Element) throws -> Bool) rethrows -> Element? {
guard let index = try firstIndex(where: predicate) else { return nil }
return remove(at: index)
}
}

var strings = ["Hello","Playground","World"]
strings.removeFirst("Hello")
print(strings) // "["Playground", "World"]\n"
strings.removeFirst { $0 == "Playground" }
print(strings) // "["World"]\n"


Related Topics



Leave a reply



Submit