There are three main collection types in Swift:

  • Arrays
  • Sets
  • Dictionaries

All container types support the following:

  • count
  • isEmpty
  • append(item)

Arrays

Example array usage:

brush: swift
var array1 : Array<Int> = Array<Int>() // Full type name
var array2 : [Int] = [Int]()           // Shorthand form
var array3 : Array<Int> = []
var array4 = Array<Int>()
var array5 = [Int]()                   // Empty constructor
var array6 = [0, 1, 3, 7]              // Type inference: Array<Int>

var myArray Array<Int> = [Int]() // Empty array
var zeroes = [Int](count: 100, repeatedValue: 0)

myArray.append(5)

// I'm hungry. Let's make a PBJ
let pbj = ["peanut butter", "jelly", "bread"]

// Oops! Need to buy stuff
var shoppingList : [String]
shoppingList = shoppingList + pbj

shoppingList[0..2] = ["potatoes", "chips", "more potatoes"]

if !shoppingList.isEmpty {
  // Go shopping
}

// Once in supermarket
var shoppingCart : Array<String>
for grocery in shoppingList {
  shoppingCart.append(grocery)
}
// Don't forget the most important thing!
shoppingCart.insert("", atIndex: 0)

var fancyArray: [FancyClass]

for (index, fancyItem) in fancyArray.enumerate() {
  print("\(index\): \(fancyItem.fancyName()\)")
}

for fancyItem in fancyArray {
  getRidOf(fancyItem)
}

Interesting member functions:

  • isEmpty
  • append(item)
  • insert(item, atIndex: n)
  • removeAtIndex(index)
  • removeLast(): rather than using removeAtIndex(a.count)

Sets

Example set usage:

brush: swift
var letters : Set<Character>() = ["a", "b", "c"]
var letters : Set = ["a", "b", "c"]

for letter in letters.sort() {
  print("\(letter\)")
}

Interesting functions:

  • isEmpty
  • insert(item)
  • remove(item)
  • contains(item)
  • sort()
  • intersect(set)
  • exclusiveOr(set)
  • union(set)
  • subtract(set)
  • isSubsetOf(set)
  • isSupersetOf(set)
  • isStrictSubsetOf(set)
  • isStrictSupersetOf(set)
  • isDisjointWidth(set)

Interesting properties:

  • count

Dictionaries

Example dictionary usage:

brush: swift
var emptyDictionary : [Int: String]()

var cityPopulation = {}
cityPopulation["Pompeya"] = nil // Remove element after eruption

var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] // [String: String]

Interesting functions:

  • keys
  • values

Comment