What are the collection types that are available in Swift?


In this tutorial, you will learn about all the collections available in the Swift language, such as arrays, dictionaries, and sets.

Collection Types

  • Array
  • Set
  • Dictionary

These collections are generic in Swift, which means they can store values of any type but of the same kind. They can work with strings, ints, classes, structs, booleans, etc. You can store any kind of value in them and cannot insert the wrong type of value by mistake. If you define a string array, you cannot insert values of Int or any other type.

Points to note about collections

Type-safe

We know that Swift is a type-safe language, so collections are also type-safe. It means you can store any type of object in collections. But you cannot insert a value of another type.

Generics

Swift's collections are implemented as a generic collection. It means you can store any type of element in any collection. There is no separate collection for storing different types of elements. For example, you can create an array of strings, class objects, int, etc.

Mutability

Collections declared as constants using the let keyword are immutable which means you cannot alter the array elements after they are initialized. If you wish to alter the collection after initialization, make them variables using the var keyword.

Pass by value

Swift's collection types are passed by value and not by reference. When a collection is assigned to another variable or passed as an argument, a copy of the original collection is made. Changes made to a collection after it is passed to a method or assigned to another variable are not reflected in the state of the original collection.

Iteration

You can iterate over the collection using loops. You can use for-in or forEach loop to iterate over the collection’s elements. For a dictionary, you have two separate arrays for keys and values to iterate them.

Swift's collection types are very significant. Let’s dive into each of them.

Array

An array stores values of the same type in an ordered list. The array can store duplicate values. Swift’s Array type is bridged to Foundation’s NSArray class.

Syntax

You can declare an empty array like the following −

let array: [Type] = []
let array: Array<Type> = []
let array = [Type]()

You can assign elements to the array while declaring it like the following −

var arrayStrings: [String] = ["Alpha", "Beta", "Delta"] // array of strings
let arrayInts: Array<Int> = [12, 23, 34, 45] // array of integers

Subscripting

Arrays can be subscripted by passing an index integer into a pair of square brackets suffixed to the array's name like below −

Accessing an element

let stringElement = arrayStrings[2] // "Delta"
let intElement = arrayInts[3] // 45

Assign an element

You can also assign a new value to a particular index like below −

Example

var arrayStrings: [String] = ["Alpha", "Beta", "Delta"] // array of strings var arrayInts: Array<Int> = [12, 23, 34, 45] // array of integers arrayStrings[2] = "Gamma" print(arrayStrings) arrayInts[1] = 15

Output

["Alpha", "Beta", "Gamma"]

Note − To modify the array element, the array must be a variable not a constant. Also, while you are assigning a new value using a subscription, the index must be within the array's bounds otherwise the code will crash.

Below are some common methods and properties performed on an array

.append() − To append a new element at the last position.

.removeFirst() − To remove and return the first element.

.removeLast() − To remove and return the last element.

.popLast() − To pop the last element.

.reverse() − To reverse the elements.

.filter() − To filter out the array element based on a condition.

.suffix() − Returns a subsequence, up to the given maximum length, containing the final elements.

.sort() − Sorts the array in place, using the given predicate as the comparison between elements.

.isEmpty − To check whether an array is empty or not.

.count − To get the number of elements containing an array.

Dictionary

A dictionary stores the values associated with keys or in key-value form. Dictionary keys and values do not maintain order.

You can create a dictionary with keys and values and separate them using the colon (:) character.

Syntax

let dictionary: [KeyType: ValueType] = [:]
let dictionary: Dictionary<KeyType, ValueType> = [:]
let dictionary = [KeyType: ValueType]()


let dictionary1: [String: Int] = ["Alpha": 1, "Beta": 2, "Gamma": 3]
let dictionary2: Dictionary<Int, String> = [1: "One", 2: "Two", 3: "Three"]

Note − When you are not sure about the value type, you can use values of any type like the below −

var dictionary: [String: Any] = ["name": "Amit Gupta",
   "age": 22,
   "address": "New Delhi, India",
   "score": 8.9]

In the above example, you can see how to make a dictionary to store values of different types. You will use this in most of the cases in your projects. However, it is not recommended to create dictionaries with Any keyword. Always declare value types such as String, Int, etc.

Subscripting

You can read the element by passing the key name enclosed in brackets [] from a dictionary like below −

Example

var dictionary: [String: Any] = ["name": "Amit Gupta", "age": 22, "address": "New Delhi, India", "score": 8.9] if let name = dictionary["name"] as? String { print("Name found: \(name)") } else { print("name does not found") }

Output

Name found: Amit Gupta

You can assign a new value to the key name enclosed in brackets [] in a dictionary like below −

dictionary["name"] = "Rahul Gupta"

Sets

A set stores unique values of the same type in an unordered list. A set can be used instead of an array when order is not essential and when you want to ensure unique elements.

Example

var numbers: Set  = [10, 20, 30, 40]
var names: Set = ["Amit", "Rahul", "Pravin", "Sachin"]

How to insert a new element in a set:

names.insert("mohit")

Conclusion

You learned what are the collection types in Swift and how to use them. Collections play an important role in Swift language. Also, there are different methods and properties provided by Swift to perform different actions over collections. Go deep and do some practice on them.

Updated on: 22-Nov-2022

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements