Swift Arrays

Swift array is an combination of element. Each element of array is accessible by index value. The main advantage of array the element are Arrangement is an ordered form, And random element are possible to access . We can define array of using brackets ([]). And each element is separate by colon.

//Create an array of 4 integers
var myArray=[1,2,3,4]
//Display all elements of arrays


[1, 2, 3, 4]

In above example provide 4 element into an array. in this case here not mention that which kind of value would stored by array, In this situation element value is provide the data type. Let's create a empty swift array.

//Create an empty integer array
var myInts=[Int]()

//make a empty string array
var myStrings=[String]()

//make a empty float array
var myFloats=[Float]()

//make a empty double array
var myDoubles=[Double]()

//Empty array of string (type annotation)
var someStrings : [String] = []

// Empty array of integers
var someNumbers = Array<Int>() 

In this example created of 6 different empty arrays. Before access the array element, Check that how many number of element are exist in array. So we can check number of element in array by using count. Let's see an example

//Create an empty integer array
var myInts=[Int]()

print("Initial size of myInts : \(myInts.count)")

print("After  size of myInts : \(myInts.count)")


Initial size of myInts : 0
After  size of myInts : 3

In this example first make an empty array in this case array are no elements. so count result in this time are 0. but after that assigned new three elements of array. In this case count are provide 3 result.

Suppose in by mistake we are get an undefined index value or accessing the empty array elements. In both situation compiler are produced an error. See this example.

//Create an empty integer array
var myInts=[Int]()

print("size of myInts : \(myInts.count)")
//case 1
print("Access Empty array element : \(myInts[1])")

//case 2
print("Access invalid index value : \(myInts[3])")


size of myInts : 0
Fatal error: Index out of range
Current stack trace:
//... more 

So when we are not sure how many number of element are stored by array then first check it out its size. If size is zero that means array is empty at this times. There is one other mechanism are available to check array is empty or not.

//Create an empty integer array
var myInts=[Int]()

if myInts.isEmpty{
  print("Array is empty")
  print("Array are not empty")
  //put your logic here


Array is empty

isEmpty are work in boolean result when array is empty that is producing true value.

Suppose we are create an array which are contains similar values. So Swift are provide Array function to do this task. This function are accepts two parameters. first is value of element (repeating), and second is total size of array (count).

//Create an empty integer array
var playerInitialRuns=Array(repeating:0,count:11)

if playerInitialRuns.isEmpty{
  print("Array is empty")
  print("Player Initial Scores : \(playerInitialRuns)")


Player Initial Scores : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

In special cases when we need to create an array which are contain not combination of similar type elements Then we can define array in this way.

var mixedData: [Any] = []  //define array of any type
mixedData = [1,true,"Swift",2019.23,false]

print(mixedData) //display elements


[1, true, "Swift", 1099.23, false]

In above all example first declare an array after that providing the values of array element. But that is not compulsory to provide an array type when assign initial values. That is depend on situation which type of value are assign to array. If assign similar type of element then swift compiler are work smartly that are internally create array data type.

let info = [1,2,3] //Array of integers
print(info) //Display array elements 


[1, 2, 3]

There are possible to define other data type which are contains similar type of array element. There are following way to set initial value of Swift Arrays.

//Create Array element which are capable to hold any values
let mixedData: [Any] = [true ,"Swift","Any",10] 

let intData : Array<Int> = [1,4,3] //Array of integers

let floatData : Array = [1.4,4.3,1.3] //Array of Float

let stringData = ["Swift","Programming"] //Array of Strings


[true, "Swift", "Any", 10]
[1, 4, 3]
[1.3999999999999999, 4.2999999999999998, 1.3]
["Swift", "Programming"]

In above example given 4 different way to set initial value of specified array.

2d arrays in swift programming

Array is multidimensional, we can define 2d array to hold complex structures of matrix. define of 2d array is similar to 1d array but only difference is there are use one extra brackets to define. For example.

//Make empty 2d arrays
var twoDimensionalArray = [[Int]]()
//assign value 2d array



[[1, 2, 3], [11, 22, 33, 44]]

In this example create an 2d array of integers. the statement of [[Int]] are provided the information of compiler that is not and simple array, brackets are describe that information.

Arrangement of 2d array element are row by row. There possible to define n rows in 2d array that is depends upon situations. In this example defined 2 rows.

[1,2,3], //first row
[11,22,33,44] //second row

The swift array is advanced, There is possible to define different amount of element in every rows. In above example first row is contains 3 elements. And second row is contains 4 elements.

In case suppose we need to create exact NXM matrix structure of similar data value. N is rows and M is columns. so We can use Array() methodes. See this example

let rows=5,columns=6,dataValue=1

var graphNodes=Array(
repeating : Array( repeating:dataValue , count:columns) ,  count:rows)

//Display array elements


[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]

There are possible to access row element in following ways.

var alphabets=[
print("Display 1'st Rows : \(alphabets[0])")
print("Display 2nd Rows  : \(alphabets[1])")
print("Display 3rd Rows  : \(alphabets[2])")

//Access Rows and columns pair key element
print("Display 3rd Rows first element : \(alphabets[2][0])")


Display 1'st Rows : ["A", "B", "C", "D"]
Display 2nd Rows  : ["a", "b", "c"]
Display 3rd Rows  : ["One", "two", "Three"]
Display 3rd Rows first element : One

That is similar to access element of C , Java programming. And using of For loop, can be iterating every 2d array elements. See this example.

var alphabets=[
//iterate row by rows
for rows in alphabets {
  //iterate by rows column
  for element in rows {
    print(" \(element)",terminator : "  ")
  print(" ")


 A   B   C   D   
 a   b   c   
 One   two   Three

Operation of Swift Arrays

Add new Elements: Collection of array element are mutable, We can modified existing array element and also add new element of array in following ways.

//Create an array of 4 integers
var myArray=[1,2,3,4]
//Before add a new arrays element
//display, after add a arrays element


[1, 2, 3, 4]
[1, 2, 3, 4, 5]

append() function are add a new element at the end position of given array. But in case we are need to add new element at front of array in this situation we can use insert function.

//Create an array of 4 integers
var myArray=[1,2,3,4]

//Before add a new arrays element
print("Before add array elements : \(myArray)")

//add element at beginning of array

//display, after add arrays element
print("After add array elements : \(myArray)")


Before add array elements : [1, 2, 3, 4]
After add array elements : [5, 1, 2, 3, 4]

This is an basic example of insert(_,at:position) function. This function are accepting two parameters, first is an insert value and second is inserted position.

One other way to add few new elements at beginning of array position. That is concatenation of two different array which is contain similar data elements.

var myData=[7,8,9]

print("Before add new elements: \(myData)")

//add new element + old element     
myData=[1,2,3] + myData

print("After add new elements: \(myData)")


Before add new elements: [7, 8, 9]
After add new elements: [1, 2, 3, 7, 8, 9]

In this example are added new element at beginning of array. That is very effective to add more than one elements.

We can also add multiple array element at the end of array position by using append(contentsOf:[]) method..

var item=[1,2,3]
print("Before: \(item)")
item.append(contentsOf: [100,900,500])//add new elements
print("After: \(item)")


Before: [1, 2, 3]
After: [1, 2, 3, 100, 900, 500]

Remove Elements: There are three standard method to remove array elements. removeLast() to remove last element, removeFirst() to remove first element and remove(at:index) to remove specific index value. all three function are remove array element. And also returning delete value.

var days=["sun","mon","tue","wed","thur","frid","sat"]
var element=" "
print("Before Remove Element: \n \(days)")

//remove last element
print("After Remove (\(element)) Last Element: \n \(days)")

//remove First element
print("After Remove (\(element)) First Element:\n \(days)")

print("After Remove (\(element)) second Element:\n \(days)")


Before Remove Element: 
 ["sun", "mon", "tue", "wed", "thur", "frid", "sat"]
After Remove (sat) Last Element: 
 ["sun", "mon", "tue", "wed", "thur", "frid"]
After Remove (sun) First Element:
 ["mon", "tue", "wed", "thur", "frid"]
After Remove (wed) second Element:
 ["mon", "tue", "thur", "frid"]

In this example are given 3 method which are remove specific index element. If in case, when we need to remove all element to existing array so we can do following way.

//Define array elements
var testOne=[1,2,3,4]
var testTwo=testOne+[5]
var testThree=testOne+[6,7]

print("Before Set Empty")

testOne=[] //Set empty array
testTwo.removeAll() //remove all element by function

print("After Set Empty")


Before Set Empty
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 6, 7]
After Set Empty

Sort array element: There are sorted(by:) function are available to sort array element in ascending and descending order.

//array element
let data=[8,7,2,4,9,1,34,13] 

//sorted element in ascending order 
let ascendingOrder=data.sorted()

//sort by descending order 
let descendingOrder=data.sorted(by: >) 

print("data : \(data)")
print("ascendingOrder : \(ascendingOrder)")
print("descendingOrder : \(descendingOrder)")


data : [8, 7, 2, 4, 9, 1, 34, 13]
ascendingOrder : [1, 2, 4, 7, 8, 9, 13, 34]
descendingOrder : [34, 13, 9, 8, 7, 4, 2, 1]

Get min and max element:

let salary=[12,44,56,11,23,12,24.12]
let maxSalary = salary.max()! //get max element
let minSalary = salary.min()! //get min element



Get array index by element value

//make a string array
var operation=["copy","past","select","click"]
var value="click" //find value
if let index=operation.index(of:value){
    print("index: \(index)")
    print("This \(value) are not exist in array")


index: 3

but note that index(of:) are base on value when two or more than two element are exist in array then it will return first find element index.

Slice array elements :

//Example to Slice array elements
var dataInfo=[0,1,2,3,4,15,16,17,18,19,20]
let firstSlice=dataInfo[0..<5] //(0..4)
let secondSlice=dataInfo[5..<dataInfo.count]
print("Array  :\(dataInfo)")


Array  :[0, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20]
firstSlice:[0, 1, 2, 3, 4]
secondSlice:[15, 16, 17, 18, 19, 20]

Separating particular data elements:

Suppose we are create a array which are contain different different data type elements. In this case we are need to separate particular data type, Then we can solve this way.

//Given array
let anyElements: [Any] = [2010,10.201,false,"Make array","2021"]

//Separated string elements
let stringElement = anyElements.flatMap { $0 as? String }

//Separated integer elements
let numbersElements = anyElements.flatMap { $0 as? Int }

//Separated Bool elements
let booleanElements = anyElements.flatMap { $0 as? Bool }

//Separated Double elements
let doubleElements = anyElements.flatMap { $0 as? Double }

print("Given Array : \(anyElements)" )
print("stringElement : \(stringElement)")
print("numbersElements : \(numbersElements)" )
print("booleanElements : \(booleanElements) ")
print("doubleElements  : \(doubleElements) ")


Given Array : [2010, 10.201000000000001, false, "Make array", "2021"]
stringElement : ["Make array", "2021"]
numbersElements : [2010]
booleanElements : [false] 
doubleElements  : [10.201000000000001] 

Segregate specified elements

Suppose given array are contain an integer elements. And we are separated specified element value to an array. For example separating Even and Odd values. Then we can do this way.

let numberElements=[1,12,3,4,5,6,7,8,11,22,10]

let evenData=numberElements.filter{$0 % 2 == 0}

let oddData=numberElements.filter{$0 % 2 != 0}

print(evenData) //Display Even values
print(oddData)  //Display Odd values


[12, 4, 6, 8, 22, 10]
[1, 3, 5, 7, 11]

In above program are used array.filter to check even and odd elements. We can also implement solution of this problem programmatically. See This example.

let numberElements=[1,12,3,4,5,6,7,8,11,22,10]

var evenData = [Int]() //empty array

var oddData  = [Int]() //empty array

for element in numberElements{

print(evenData) //Display Even values
print(oddData)  //Display Odd values


[12, 4, 6, 8, 22, 10]
[1, 3, 5, 7, 11]

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment

© 2021, kalkicode.com, All rights reserved