Swift Array – basic introduction


Swift Array

Swift array

Swift Array

An array in Swift, and any other programming language who support arrays, is a list of data. Those data can be any datatype. Integers, double, float, string and even classes. I will just show a few examples here. For a complete list and full documentation I suggest you head over to Apples Swift documentation, by click that link.

Swift array of integers

Say we need a list of integers for our software. Some pre-declared integers in a list of integer constants. Because we dont need to change them. Here is how to do that.

let myIntegers = [1, 3, 5, 10, 25, 100, 1000]

Ok, so how do we use that array of constants? I need to print the first and the last item now.

print(myIntegers[0])  // Printing the first item

print(myIntegers[6])  // Printing the last item

print(myIntegers.last)  // Printing the last item

So what if myIntegers was variables instead of constant? And I wanted to change the value of the 1st, 2nd and the last one?

myIntegers[0] = 10 // Changing the first item

myIntegers[1] = 15 // Changing the second item

MyIntegers.last = 99 // Changing the last item

Swift Array – Empty

Seems easy enough. But I need an empty array to populate later in my software. How do I do that?

var myIntegers = [Int]() // Declare an empty array of type Int

So how do I add items to this

myIntegers.append(5) // Your array now contain 1 value. The value 5.

Swift Array – insert

Actually I need to insert a new value before the one I added. Can I do that? Yes.

myIntegers.insert(12, atIndex:0) // The value 12 was inserted at the beginning of the array.

You can use this to insert values where ever you want in the array.

Swift Array – remove

I have a huge array, and I need to remove my 5th value and the last value. Is that even possible? Yes.

myIntegers.removeAtIndex(5)

myIntegers.removeLast()

Swift Array – remove duplicates

My string array that  contains html links has a lot of duplicates. Is it possible to remove duplicates easily? Yes it is.

First you convert the array to a Set and then back to an Array. Set doesn’t contain duplicates, since it is not a list like an array. Here is how.

myStringArray = Array(Set(myStringArray))    // Your duplicates are now gone.

Swift Array – default value

Can I declare an array with a default value? I need an array of 10 values with the same value until I change them.

var myDefaultArray = [Double](count: 10, repeatedValue: 5.0)

Thats it for now about array. If you want to learn more and specific situations about array, I suggest you head over to iswift.org.

Happy arraying!

Have any Question or Comment?

Leave a Reply