Book Image

Beginning Swift

By : Rob Kerr, Kåre Morstøl
Book Image

Beginning Swift

By: Rob Kerr, Kåre Morstøl

Overview of this book

Take your first foray into programming for Apple devices with Swift.Swift is fundamentally different from Objective-C, as it is a protocol-oriented language. While you can still write normal object-oriented code in Swift, it requires a new way of thinking to take advantage of its powerful features and a solid understanding of the basics to become productive.
Table of Contents (10 chapters)


A Dictionary is an unordered collection of mappings/associations from keys to values. It is very similar to a Set and has the same performance, but stores a key/value pair, and only the key has to be Hashable. It can be used for storing preferences, or when you have a group of named values that are either too many or change too often to be hardcoded. Then, you can use the names as keys.

The full name is Dictionary<Key, Value>, but it is more commonly written as [Key: Value].

Dictionary ignores the order in which values are added or removed, and may change it arbitrarily, just like Set.

Working with Dictionaries

Here are a few basic operations with dictionaries:

  1. Create a dictionary and print it to observe that the order is not preserved:

           var numbers = [0: "zero", 1: "one", 10: "ten", 100: "one hundred"]
           print(numbers) // [100: "one hundred", 10: "ten", 0: "zero", 1: "one"]
  2. Add or change a value: