Swift Tutorial
Swift Data Types
Swift Control Flow
Swift Functions
Swift Collections
Swift OOPs
Swift Additional Topics
In Swift, if you want to remove the last element from an array, you can use the removeLast()
method of the Array
type. This method removes and returns the last element of the array.
Here's how you can do it:
var numbers = [1, 2, 3, 4, 5] if !numbers.isEmpty { let removedNumber = numbers.removeLast() print("Removed number: \(removedNumber)") print("Remaining numbers: \(numbers)") } else { print("The array is empty.") }
In this example, removeLast()
will remove the number 5
from the numbers
array.
Note: It's essential to ensure that the array isn't empty before calling removeLast()
. If you call removeLast()
on an empty array, it will trigger a runtime crash. In the example above, we use a condition (if !numbers.isEmpty
) to check if the array has elements before attempting to remove the last one.
Swift remove last element from array:
removeLast()
method.var numbers = [1, 2, 3, 4, 5] numbers.removeLast() print(numbers) // Output: [1, 2, 3, 4]
Remove the final element from Swift array:
removeLast()
method.var fruits = ["Apple", "Banana", "Orange"] fruits.removeLast() print(fruits) // Output: ["Apple", "Banana"]
How to delete the last item from array in Swift:
removeLast()
method.var colors = ["Red", "Green", "Blue"] colors.removeLast() print(colors) // Output: ["Red", "Green"]
Swift array removeLast method:
removeLast()
method is specifically designed to remove the last element from a Swift array.var names = ["Alice", "Bob", "Charlie"] names.removeLast() print(names) // Output: ["Alice", "Bob"]
Swift array dropLast function:
dropLast(_:)
function can be used to remove a specified number of elements from the end of a Swift array.var elements = [1, 2, 3, 4, 5] elements = Array(elements.dropLast()) print(elements) // Output: [1, 2, 3, 4]
Delete last element from array in Swift:
removeLast()
method.var items = ["Item1", "Item2", "Item3"] items.removeLast() print(items) // Output: ["Item1", "Item2"]
Swift array remove element at last index:
remove(at:)
method and specify the last index.var letters = ["A", "B", "C", "D"] let lastIndex = letters.count - 1 letters.remove(at: lastIndex) print(letters) // Output: ["A", "B", "C"]
Remove last item from array in Swift example:
removeLast()
method.var items = ["Apple", "Orange", "Banana"] items.removeLast() print(items) // Output: ["Apple", "Orange"]
Swift array pop last element:
popLast()
method is specifically designed to remove and return the last element from a Swift array.var cities = ["Paris", "London", "Berlin"] if let poppedCity = cities.popLast() { print("Popped: \(poppedCity)") } print(cities) // Output: ["Paris", "London"]