Swift Collections : Arrays

So let’s talk about arrays in swift. Basically arrays are used for gathering the same type of datas in a group. Arrays store data in an ordered collection. That means you will be able to know the specific address of your data. In arrays we use the index to access data. Each data has an index number. As we said, arrays store the data which has the same data type. Therefore we cannot store string value into an integer array. So let’s begin.

Below code shows a simple definition of arrays :

let days = ["mon","tue","wed","thu","fri","sat","sun"]

We defined a days array with the let keyword. That means we cannot change it’s value later. To do a mutable array we can use the var keyword as defining the array. Just like that :

var days = ["mon","tue","wed","thu","fri","sat","sun"]

As you may see in the preceding two examples we predefined the array’s value. Of course we can define an array without default value, in this case an empty array. But we must specify the type of it. Take a look at the code below:

var days : [String]()
var years : [Int]()
var weights : [Double]()

We can also define an array with a certain size and value. To do that we use repeating and count properties.

var days = [String](repeating: "default day", count: 7)

The above code initiates an array that has seven elements with default values. In this case the default value is “default day” . So how can we access the elements in the array ?

It is pretty easy. We use a specific index of each element to access it.  Let’s look at the code below :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
print(days[0])
print(days[6])

When we run the above code, it will print out the first and the last element of the days array. We can also use first or last  properties to access the first and last element of an array. In this case the code would be like that :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
print(days.first)
print(days.last)

To check whether an array is empty, we can use the isEmpty  property. This property returns true if the array is empty. Look at the code below and see how to check an array whether it is empty or not :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
var arrayAges = [Int]()
if days.isEmpty {
    print("days array is empty")
}
if arrayAges.isEmpty {
    print("arrayAges array is empty")
}

When you run the above code, the output will be “arrayAges array is empty” because the days array was initiated with elements while arrayAges was empty. We can also shuffle the element in an array with the shuffle() method. Suppose you have some questions in an array and you want to shuffle it before showing the questions to the user. Of course there are many different other use cases. arrayName.Shuffle() command will do that shuffling for you.

To update an element in an array we can use the same method as we  access an element. See below :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
days[4] = "Beautiful friday"

The fourth element of the days array will be changed from “fri” to “Beautiful friday”. It is pretty easy. What about adding new value to an array ?  append() method is very useful to add a value to an array dynamically. The value will be added at the end of the array when we use append methods to add a value. Let’s look at how can we use it :

var users = ["user1","user2"]
users.append("user3")

The users array now contains “users3” value as its third element. You may say “What should I do if I want to add a new value to a specific index rather than adding at the end of the array. Do not worry. There is also an insert() method that allows us adding new values to a specific index.

var days = ["mon","tue","wed","thu","fri","sat","sun"]
days.insert("fri2", at:5)

Above code basically add an element called “fri2” into the fifth index of days array. The days array content will be like this :

var days = ["mon","tue","wed","thu","fri","fri2","sat","sun"]

We can remove elements from an array. There are three methods to do that.

These are :

  • removeLast()
  • remove(at:)
  • removeAll()

As you may guess, the removeLast() method removes the last element of the array. remove(at:) method requires an index of the element that will be deleted. removeAll() method removes all the elements in the array. Below code shows how to use these methods:

var days = ["mon","tue","wed","thu","fri","sat","sun"]
days.removeLast() // the "sun" will be deleted
days.remove(at: 2) // "wed" will be deleted
days.removeAll() // rest of the all elements will be deleted.

We can merge arrays with the + operator. Take a look at the below code :

let numbers1 = [1,2,3]  
let numbers2 = [4,5,6]
var mergedArray = numbers1 + numbers2

Now the mergedArray will have [1,2,3,4,5,6] values. We can also retrieve a subarray from an array. To do that, we use the range operator. Here is an example :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
var workingdays = days[0...4]

The workingdays array will have [ “mon”,tue”,”wed”,”thu”,”fri”] values. Because we defined the range from 0 to 4. These ranges represent indexes. The operator that we’ve used above is known as the two-sided range operator. There is also the one-sided range operator. We can apply one-sided range operator to above example and get the same results :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
var workingdays = days[...4]

When we initiate workingdays array, we are getting the elements from beginning to the fourth element (fourth included). The result will be the same. [ “mon”,tue”,”wed”,”thu”,”fri”]

There are some useful algorithms that we can apply to an array. These are

  • Sort / Sorted
  • Filter
  • Map
  • Count with rule
  • forEach
  • for-in

We use the Sort() method to sort the array in descendant or ascendant order. This method takes two arguments ($0 and $1) . The example that is shown below sorts an array in ascending order :

var numbers = [10,4,6,5,3,1]
numbers.sort(){ $0 < $1 }

numbers array elements will be sorted like that : [1,3,4,5,6,10] . { $0 < $1 } means the first element must be less than the second element. This rule is applied to each element. If the rule returns false value then the elements will be replaced. Let’s suppose you want to sort an array but you want to sort it into another array without changing the original array. We can use the sorted() function to do that. With that function the original array won’t be changed. Take a look :

var numbers = [10,4,6,5,3,1]
let sortedNumbers = numbers.sorted(){ $0 < $1 }

The Filter algorithm allows us to create a new array by filtering the original array. Below example explains it very well :

var numbers = [10,4,6,5,3,1]
var filteredNumbers = numbers.filter{$0 > 5 && $0 < 10}

The filteredNumbers will have this value : [6] . Because there is only one value that is greater than 10 and less than 5 in the numbers array.We can apply logic to each element of an array by using the map  algorithm. Let’s go on with example :

var scores = [50,60,70,80]
let newScores = scores.map{ $0 / 10}

The map algorithm iterates each element and divides it by 10. The newScores array will have these values : [5,6,7,8].

We can count an array with a specific rule. See below :

var scores = [50,60,70,80]
var bestScores = scores.count{ $0 >= 70 }

The bestScores value will get the value 2. Because there are 2 values that equal or greater than 70. We can also use forEach loop to iterate each item of an array. Look at the example below :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
days.forEach{ print($0) }

When we run the above code it will print out all the elements of the days array. We can also use the for-in loop to iterate each element. As using for-in loop we can also access each element’s index as well as the it’s value. To do that we can use the enumerated() method. Let’s see the both usage below  :

var days = ["mon","tue","wed","thu","fri","sat","sun"]
 
for day in days {
    print("Today is \(day)")
}
 
for (index,day) in days.enumerated(){
    print("\(index) \(day)")
}

So in this post we’ve covered the arrays and it’s usage in swift. See you in the next one.

You may also like...