| by Arround The Web | No comments

Swift Array – Remove

In this Swift guide, we will see the remove() method in the Array Collection.

Before going to discuss this method, we will see what an Array is.

Swift Array

Array in Swift is a Collection that stores multiple elements with the same data type.

In Swift, we have to specify the datatype to represent the data type of Array while creating an array. It is also possible to create elements in an Array without specifying any data type.

remove()

remove() in Array Swift can be used to remove an element at a specified position. We can remove the element at a particular position using index value.

Syntax:

swift_array.remove(at:index)

 
Parameter:

It takes one parameter.

at: takes an index position which is an integer value that specifies the position of the Element to be removed.

Return:

It returns an Array with the remaining elements.

Example 1:

Create a Swift Array that stores ten integer values. Let’s remove some elements one by one.

//create an Swift Array with 10 integer elements
var swift_array:[Int] = [34,56,32,56,78,90,67,89,90,12]

// Actual swift array
print("Actual Swift Array: ", swift_array)

//remove element present at index-9
swift_array.remove(at:9)

//remove element present at index-3
swift_array.remove(at:3)

//remove element present at index-6
swift_array.remove(at:6)

//remove element present at index-0
swift_array.remove(at:0)

// Final swift array
print("Final Swift Array: ", swift_array)

 
Output:

Explanation:

Line -2:


We created an Array named swift_array that holds 10 integer values.

Line -8-17:


We are removing elements present at indices – 9,3,6, and 0.

So, the Updated Swift array is:

[56, 32, 78, 90, 67, 90]

 

Example 2:

Create a Swift Array that stores five strings. Let’s remove some elements one by one.

//create a Swift Array with 5 strings.
var swift_array:[String] = ["one","two","three","four","five"]

// Actual swift array
print("Actual Swift Array: ", swift_array)

//remove element present at index-3
swift_array.remove(at:3)

//remove element present at index-2
swift_array.remove(at:2)

// Final swift array
print("Final Swift Array: ", swift_array)

 
Output:

Explanation:

Line -2:


We created an Array named swift_array that holds 5 strings.

Line 8-11:


We are removing elements present at indices – 3 and 2

So, the Updated Swift array is:

[“one”, “two”, “five”]

 

Conclusion

So, we saw how to remove an element to the swift array using remove() method. We can remove an element at a particular position using index value. It takes an index position which is an integer value that specifies the position of the Element to be removed. Make sure that you have to specify the Index value within the specified range only for removing an element.

Share Button

Source: linuxhint.com

Leave a Reply