Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
swift
communitycreator

What is array.popLast() in Swift?

Theodore Kelechukwu Onyejiaku

Overview

In Swift, we use the popLast() method to remove and return the last element of an array.

Syntax

arr.popLast()

Parameters

This method does not take any parameters.

Return value

The last element of an array is returned if the array is not empty. Otherwise, nil is returned.

Example

// create an array
var gnaam = ["Google", "Netflix", "Amazon", "Apple", "Facebook"]
print("Initial array is ", gnaam)
// remove last element
let poppedEl = gnaam.popLast()!
print("Last Element Removed: ", poppedEl)
// add new element 
gnaam.append("Meta")
// print new array values
for coy in gnaam{
    print(coy)
}
Removing the last element from an array in Swift

Explanation

  • Line 2: We create an array gnaam. It contains the names of the big tech companies.
  • Line 3: We print the array to the console.
  • Line 5: We call the popLast() method on the array and store the popped element on a variable called poppedEl.
  • Line 6: We print the popped element.
  • Line 8: We append the value "Meta" to the array.
  • Line 10: We use the for-in loop to print each element of the array.

RELATED TAGS

array
swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring