6 Collections

WHAT YOU WILL LEARN IN THIS CHAPTER:                              

  • How to create an array
  • How to retrieve elements from an array
  • How to insert elements into an array
  • How to modify elements in an array
  • How to append elements to an array
  • How to check the size of an array
  • How to remove elements from an array
  • How to iterate over an array
  • How to test arrays for equality
  • How to create a dictionary
  • How to retrieve elements from a dictionary
  • How to insert elements into a dictionary
  • How to modify elements in a dictionary
  • How to append elements to a dictionary
  • How to check the size of a dictionary
  • How to remove elements from a dictionary
  • How to iterate over a dictionary
  • How to test dictionaries for equality

Swift provides two types of collections for storing data of the same type: arrays and dictionaries. An array stores its items in an ordered fashion, whereas a dictionary stores its items in an unordered fashion and uses a unique key to identify each item.

In Swift, both the array and the dictionary are very clear about the type of data they are storing. Unlike the NSArray and NSDictionary classes in Objective-C, arrays and dictionaries in Swift use either type inference or explicit type declaration to ensure that only specific types of data can be stored. This strict rule about data types enables developers to write type-safe code.

ARRAYS

An array is an indexed collection of objects. The following statement shows an array containing three items:

 var OSes = ["iOS", ...

Get Beginning Swift Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.