Swift 3.0 – data structures

ref – https://www.raywenderlich.com/123100/collection-data-structures-swift-2

Arrays

  • An array is a group of items placed in a specific order, and you can access each item via an index — a number that indicates its position in the order. When you write the index in brackets after the name of the array variable, this is subscripting.
  • Swift arrays are immutable if you define them as constants with let, and mutable if you define them as variables with var.
  • In contrast, a Foundation NSArray is immutable by default. If you want to add, remove or modify items after creating the array, you must use the mutable variant class NSMutableArray.
  • An NSArray is heterogeneous, meaning it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Array is guaranteed to contain only one type of object.
    However, you can still define a single Swift Array so it stores various types of Cocoa objects by specifying that the one type is AnyObject, since every Cocoa type is also a subtype of this.

The primary reason to use an array is when the order of variables matters. Think about those times when you sort contacts by first or last name, a to-do list by date, or any other situation when it’s critical to find or display data in a specific order.

Run time for Arrays

Accessing any value at a particular index in an array should usually be O(1)
Searching for an object at an unknown index will generally be O(n).
Inserting or deleting an object will often be O(1).

Dictionaries

Dictionaries are a way of storing values that don’t need to be in any particular order and are uniquely associated with keys. You use the key to store or look up a value.

Dictionaries also use subscripting syntax, so when you write dictionary[“hello”], you’ll get the value associated with the key hello.

Like arrays, Swift dictionaries are immutable if you declare them with let and mutable if you declare them with var. Similarly on the Foundation side, there are both NSDictionary and NSMutableDictionary classes for you to use.

When to use Dictionaries

Dictionaries are best used when there isn’t a particular order to what you need to store, but the data has meaningful association.

Sets

  • A set is a data structure that stores unordered, unique values. Unique is the key word; you won’t won’t be able to add a duplicate.
  • Swift sets are type-specific, so all the items in a Swift Set must be of the same type.
  • Swift added support for a native Set structure in version 1.2 – for earlier versions of Swift, you could only access Foundation’s NSSet.
    Note that like arrays and dictionaries, a native Swift Set is immutable if you declare it with let and mutable if you declare it with var. Once again on the Foundation side, there are both NSSet and NSMutableSet classes for you to use.