As @i40West points out, removeLast is essentially a pop. That said, if you wanted to fix the compiler issues with the original code:

  1. The array might not contain class references so AnyObject wouldn’t work. You could replace that with Any (which can contain classes, structs or enums), but better to return an Element, which is what an instance of Array typealiases for whatever it actually contains.

  2. self.last returns an optional (in case the array is empty). You could choose to return an optional from pop similar to last, or just assert if the array is empty similar to removeLast.

  3. Since pop is modifying self (it removes an entry) and Array is a struct, you need to mark the function as mutating.

So the full version, assuming removeLast didn’t return a value, could be something like:

extension Array {
    mutating func pop() -> Element {
        precondition(self.startIndex != self.endIndex, "Attempt to pop from an empty array")
        let out = self.last
        self.removeLast()
        return out!
    }
}
Answer from Airspeed Velocity on Stack Overflow
Discussions

how to remove an item from a list based on the item's shallow reference?
I know what a deep copy is, but a shallow reference? More on reddit.com
🌐 r/swift
10
2
October 22, 2023
removing from an array inside a function – Swift – Hacking with Swift forums
SPONSORED The fastest way to learn Swift? Build a real app. More on hackingwithswift.com
🌐 hackingwithswift.com
June 26, 2022
How do I remove an item from an array?
I am working on a challenge asking me to use the removeAtIndex() method to remove the 6th item (index 5) from an array. Since removeAtIndex() has been replaced in Swift 3, I cannot test my code in XCode. More on teamtreehouse.com
🌐 teamtreehouse.com
1
October 12, 2016
How to remove an element from an array in Swift - Stack Overflow
How can I unset/remove an element from an array in Apple's new language Swift? Here's some code: let animals = ["cats", "dogs", "chimps", "moose"] How could the element animals[2] be removed from... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Swift Forums
forums.swift.org › using swift
Array removeFirst - Using Swift - Swift Forums
April 4, 2022 - Is it possible to do "get and remove first element of array" in one go · I don't think so, but if you need to call this function repeatedly, e.g. in parsing, you could perhaps first turn your array into an ArraySlice and then use .popFirst(). Since the slice keeps the underlying collection ...
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-remove-the-first-or-last-item-from-an-array
How to remove the first or last item from an array - free Swift example code and tips
May 28, 2019 - If you call removeLast() on an empty array, your app crashes. So, in this example last1 will contain 5 and last2 will contain 4: var numbers = [1, 2, 3, 4, 5] let last1 = numbers.popLast() let last2 = numbers.removeLast()
🌐
Medium
pubududilshan.medium.com › different-methods-to-remove-the-last-item-from-an-array-in-swift-1c65e069b7cd
Different methods to remove the last item from an array in Swift | by Pubudu Dilshan | Medium
November 28, 2024 - Arrays are one of the most widely used data structures in Swift, and we deal with a lot of array manipulations. One such manipulation is the removal of the last element from an array. The three useful methods to remove an element from an array are dropLast(), popLast(), and removeLast() We have an array of fruits, namely, [“Apple”,”Orange”,”Banana”]. Using the dropLast() method on the array will remove the last element (‘Banana’ in our case), and it will return the remaining array elements.
Find elsewhere
🌐
Team Treehouse
teamtreehouse.com › community › how-do-i-remove-an-item-from-an-array
How do I remove an item from an array? (Example) | Treehouse Community
October 12, 2016 - iOS Swift 2.0 Collections and Control Flow Introduction to Collections Working with Arrays · 874 Points · Posted October 12, 2016 12:04am by Brook Wolcott · 874 Points · I am working on a challenge asking me to use the removeAtIndex() method to remove the 6th item (index 5) from an array.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › pop
Array.prototype.pop() - JavaScript | MDN
The pop() method is a mutating method. It changes the length and the content of this. In case you want the value of this to be the same, but return a new array with the last element removed, you can use arr.slice(0, -1) instead.
🌐
Programiz
programiz.com › swift-programming › library › array › removefirst
Swift Array removeFirst() (with Examples)
The removeFirst() method removes the first element from the array. The removeFirst() method removes the first element from the array. Example var brands = ["Dell", "Apple", "Razer"] // removes and returns first element from brands print(brands.removeFirst()) // Output: Dell removeFirst() Syntax ...
🌐
GeeksforGeeks
geeksforgeeks.org › swift › how-to-remove-the-first-element-from-an-array-in-swift
How to Remove the First element from an Array in Swift? - GeeksforGeeks
June 2, 2022 - It is an optional parameter and it is used to remove the number of elements from the starting of the array · Return Value: This function returns the removed value ... // Swift program to remove first element from the array import Swift // Creating ...
🌐
Donny Wals
donnywals.com › remove-instances-of-an-object-from-an-array-in-swift
Removing a specific object from an Array in Swift – Donny Wals
April 23, 2024 - The closure you pass to removeAll(where:) is executed for every element in the Array. When you return true from the closure, the element is removed from the Array.
🌐
Reddit
reddit.com › r/swift › how to remove element from an array in a for each loop
r/swift on Reddit: How to remove element from an array in a for each loop
July 18, 2022 -

Hello so I have an observable object class containing an array, and button in my view that adds to that array just fine, however I’m having trouble figuring out a way to have each element in the array, have its own button that removes it,

I’ve been able to render it, but as far as the actual button action, I can’t quite understand the syntax to remove the correct index in the array.

Top answer
1 of 2
2
Usually it's best to use identifiable objects and remove the item by id. Otherwise when you create the object you'll need to feed in the index and those will change whenever you remove other items. I would probably pass a "remove(id: UUID)" closure to View objects that they can call to remove themselves. In the parent view, that method would do something like: array.removeAll(where: {$0.id == id})
2 of 2
-1
How I would implement this depends on whether your array contains primitive or identifiable objects. Here are both implementations: import SwiftUI class Car { public let id = UUID() } class MyObject: ObservableObject { @Published private(set) var cars = [Car]() @Published private(set) var ints = [Int]() func addCar() { self.cars.append(Car()) } func addInt() { self.ints.append(Int.random(in: 1...10)) } func removeCar(id: UUID) { if let index = self.cars.firstIndex(where: { $0.id == id }) { self.cars.remove(at: index) } } func removeInt(at position: Int) { if self.ints.count-1 >= position { self.ints.remove(at: position) } } } struct ContentView: View { @StateObject private var myObject = MyObject() var body: some View { VStack { ForEach(self.myObject.cars, id: \.id) { car in HStack { Text("Car \(car.id.uuidString)") Button("Remove") { self.myObject.removeCar(id: car.id) } } } ForEach(Array(zip(self.myObject.ints.indices, self.myObject.ints)), id: \.1.self) { index, int in HStack { Text("Int \(int)") Button("Remove") { self.myObject.removeInt(at: index) } } } Button("Add Car") { self.myObject.addCar() } Button("Add Int") { self.myObject.addInt() } } } }
🌐
GeeksforGeeks
geeksforgeeks.org › swift › how-to-remove-the-last-element-from-an-array-in-swift
How to Remove the last element from an Array in Swift? - GeeksforGeeks
June 2, 2022 - In Swift, using the removeLast() function we can also remove multiple elements from the ending of the array. To do this we only need to pass the number which represents the total number of elements to remove from the array in the function.
🌐
Programiz
programiz.com › swift-programming › library › array › remove
Swift Array remove() (With Examples)
The remove() method removes an element from the array at the specified index. The remove() method removes an element from the array at the specified index. Example // create an array var prime = [2, 3, 5, 7, 9, 11] // remove 9 from the array prime.remove(at:4) // print updated prime array ...