Basics of Arrays

In swift, arrays are useful to store the same data type of multiple values in an ordered manner. In array, we can store the same value in multiple times at different positions based on our requirements.

In swift arrays, we can store any kind of elements like either strings or integers or other element types based on our requirements.

Empty arrays:

var array: [String] = [] // type annotation + array literal
var array = [String]() // invoking the [String] initializer
var array = Array() // without syntactic sugar

An array of string elements:

var names = ["Adam", "Danny", "Pavel"]

Array literals:

let arrayOfInt = [1, 3, 5]


In Swift, we can exponentiate Doubles with the built-in pow() method:


In the code below, the base (10) is set to the power of the exponent (2) :

let number = pow(10.0, 2.0) // Equals 100

Deleting a POD File

Sometimes it happens that the installed framework stops working correctly and causes errors. In this case, deleting the POD file and reinstalling it can help.

$ sudo gem install cocoapods-deintegrate cocoapods-clean
$ pod deintegrate
$ pod clean
$ rm Podfile

Random number generation

arc4random_uniform(someNumber: UInt32) -> UInt32

This gives you random integers in the range 0 to someNumber – 1.

The maximum value for UInt32 is 4,294,967,295.

let day = arc4random_uniform(31) + 1 // 1...31
let year = 2010 + arc4random_uniform(10) // random year

Property Observers

Property observers respond to changes to a property’s value.

var myProperty = 5 {
willSet {
print("Will set to \(newValue). It was previously \(myProperty)")
didSet {
print("Did set to \(myProperty). It was previously \(oldValue)")
myProperty = 6
// prints: Will set to 6, It was previously 5
// prints: Did set to 6. It was previously 5

Creating a Variable

Declare a new variable with var, followed by a name, type, and value:

var num: Int = 10
var str: String = "Hello World!"

Variables can have their values changed:
num = 20 // num now equals 20

Unless they’re defined with let:
let num: Int = 10 // num cannot change

Swift infers the type of variable, so you don’t always have to declare variable type:
var ten = 10 // num is an Int
var txt = "Hello!" // text is a String
var pi = 3.14 // pi is a Double
var floatPi: Float = 3.14 // floatPi is a Float