Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
array
remove
communitycreator

What is the remove() method of an array in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

An array’s elements can be removed in Swift using the remove() method.

We only have to pass the element’s index to delete the elements.

Syntax

arr.remove(at: index)
Syntax to remove an element in an array in Swift

Return type

It’s return type is void.

Parameters

index: This refers to the index position of the array to remove. In this case, the array is arr.

Code example

// create an array
var vowels = ["a", "e", "p", "i", "o", "u", "k"]
// print initial array
print(vowels)
// remove element
vowels.remove(at : 2) // remove "p"
//print new array
print(vowels)
// remove element
vowels.remove(at : 5) // remove "k"
// print array
for letter in vowels{
print(letter)
}
Remove elements from an array in Swift

Explanation

  • Line 2: We create an array named vowels.
  • Line 4: We print the array’s values to the console.
  • Line 6: An element at index 2 is removed. This is the character "p". After this, the array has six remaining elements.
  • Line 8: The array will not remain the same since an element has been removed. So, we print the modified array on this line.
  • Line 10: An element at index 5 is removed from the modified array.
  • Line 12: We print the elements of the modified array using the for-in loop.

RELATED TAGS

swift
array
remove
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring