Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift Array removeAll()
In this tutorial, we will learn about the Swift Array removeAll() method with the help of examples.
The removeAll() method removes all the elements from the array based on a given condition.
Example
var numbers = [2,4,6,8]
// remove all elements
numbers.removeAll()
print(numbers)
// Output: []
removeAll() Syntax
The syntax of the removeAll() method is:
array.removeAll(where: condition)
Here, array is an object of the Array class.
removeAll() Parameters
The removeAll() method can take one parameter:
- condition (optional) - a closure which accepts a condition and returns a bool value. If the condition is true, the specified element is removed from array.
removeAll() Return Value
The removeAll() method doesn't return any value. It only removes elements from the array.
Example 1: Swift removeAll()
var languages = ["Swift","Java","C"]
print("Programming Languages:", languages)
// removing all elements from array
languages.removeAll()
print("Array after removeAll:", languages)
Output
Programming Languages: ["Swift", "Java", "C"] Array after removeAll: []
Example 2: Using removeAll() with where Clause
var languages = ["Swift", "C", "Objective-C"]
// remove "Objective-C" from languages
languages.removeAll(where: { $0 == "Objective-C" })
print(languages)
Output
["Swift", "C"]
In the above example, we have defined the closure {$0 == "Objective-C"} to remove "Objective-C" from the array.
$0 is the shortcut to mean that the first element of the languages array is passed into the closure.
Did you find this article helpful?