Swift Overview - Collections

Array

Initializing Arrays

Initializer syntax - explicitly using the constructor

var numbers = Array<Double>()  
var moreNumbers = [Double]()  

Literal syntax

var differentNumbers = [90.0, 70.0, 60.0]  

Here the array’s type can be inferred by the compiler

Array’s can hold any type of object

var  dogs = [Poodle, Golden, Pug]  

Operations

var steaks = [“ribeye”, “sirloin”, “filet”]  

Add Items

steaks.append(“flank”)  
steaks.insert(“ny strip”, atIndex: 2)  

Remove Items

steaks.removeAtIndex(1)  
steaks.count  

Retrieve Items

let bestSteak = steaks[0]  

Dictionary

Initializing Dictionaries

Initializer Syntax - explicitly using the constructor

var animalGroups = [String:String]()  
var avgAnimalLifeSpan = [String:Range<Int>]()  

Literal Syntax

var animalGroups = [“whales”:”pod”, “geese”:”flock”, “lions”:”pride”]  

Operations

Add Items

animalGroups[“monkeys”] = “troop”  

Remove Items

animalGroups[“geese”] = nil  

Update Items

animalGroups[“monkeys”] = “barrel”  
var group = animalGroup.updateValue(“gaggle”, forKey: “geese”)  

This will return an optional which is good for cases when you try to update a value that is not in the dictionary, updateValue will just return nil and add the key value pair to the dictionary

Retrieve Items

var favName = animalGroup[“whales”]  

This will return an optional because there is always a chance that that the key value pair will not be in the dictionary and will need to be unwrapped


Set

Initializing Dictionaries

Initializer syntax - explicitly using the constructor

var cutlery = Set<String>()  

Literal syntax

var cutlery = Set[“fork”, “knife”, “spoon"]  

Operations

Add Items

cutlery.insert(“chop stick”)  

Remove Items

cutlery.remove(“fork”)