Wednesday, September 21, 2016

Swift 3 - Collections - Arrays in Swift 3


In Swift 3 we have three different of collections the first is Arrays and the second is Sets then the last is Dictionaries. In this lesson we will learn about Arrays. So what is Arrays in Swift 3 and how to use it? Let's follow the following explanation.

What's Arrays in Swift?

Arrays are useful for storing ordered sets of data. Apple's definition of array is an array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.

Now let's open our playground and delete all of rows there except import UIKit. Then let's create an empty array of integers. To make an empty array just type var var_name = [Data_type] (), such as the following code :

var age = [Int] ()
So now we have an ampty array of integers. If you wanna change the data type, just change Int with another data type such as String, Float, etc.


In Swift 3 you can also declare an array such as the following code :

var someInts [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9]
So now let's add a value to these first. Let's take our someInts then hit dot (.) and we want append some values to there. Append allows us to add a new element so let's write the following code into our playground and see what happend with our playground :

someInts.append(4)
someStr.append("Ask MHS")
There's thing you have to know and understand about array, in array you just can add eleemnts at the same type. For example we have an integer of array, so the element must be an integer and can't be filled with "4" or 4.45 or true/false.

You can also append some elements into an array by doing like this :

someInts += [5, 6, 7, 8, 9]
someStr += ["Ask", "MHS"]
Okay, so what if we want to know how many elements are in our array. Because it's very common thing you need to know. For example if you had an array of people's personal data like addresses, phone numbers, then you want to know how many entries the data that have been entered. So the way we get that is by having some intense .count, and that returns a number of entries that we have.

someInts.count
someStr.count

And now, how if we want to access or print a specific element of array. Alright, such as another programming language, in Swift 3 we ca access or print a specific element of array by call it's index. In Swift 3, index of array will start from 0. So let's say we want to print 88 from someInts, so we just type :

print(someInts[2])
Alright guys, that's all about Arrays in Swift 3. In the next leoon we will learn abou Set's in Swift 3, so please stay tune on Ask MHS.

Thank you very much guys, hope this can be useful for us on learn Swift 3. If you have any questions just leave some comment below and see you next time in the next lesson.

No comments:

Post a Comment