Swift Learning (6) - Collection Types (Code Enhanced Version)
The Swift
language provides three basic collection types to store collection data: arrays (Array
), sets (Set
), and dictionaries (Dictionary
). Arrays are ordered collections of data. Sets are unordered collections with no duplicate data. Dictionaries are unordered collections of key-value pairs.
In Swift
, arrays, sets, and dictionaries must explicitly specify the types of keys and values they store, which helps prevent inserting values of the wrong type. Similarly, you can be assured that the type of the value you retrieve is correct.
Note
Swift arrays, sets, and dictionaries are implemented as generic collections.
Mutability of Collections
If you create an array, set, or dictionary and assign it to a variable, the collection will be mutable. This means you can add, modify, or remove items after creation. If you assign an array, set, or dictionary to a constant, it becomes immutable—its size and contents cannot be changed.
Note
Creating immutable collections when you don’t need to change them is a good practice. This makes your code easier to understand and allows the Swift compiler to optimize collection performance.
Arrays
Arrays store multiple values of the same type in an ordered list. The same value can appear multiple times at different positions in an array.
Note
Swift’s
Array
type is bridged to theNSArray
class inFoundation
.
Basic Array Syntax
The full syntax for arrays in Swift
is Array<Element>
, where Element
is the only allowed data type in the array. You can also use the shorthand [Element]
. Both forms are functionally identical, but the shorter form is recommended and will be used throughout this text.
var initArray: Array<String> = Array<String>()
initArray.append("hello")
print("Array of type Array<String>: \(initArray)")
---
output: Array of type Array<String>: ["hello"]
Creating an Empty Array
You can use constructor syntax to create an empty array of a specific data type.
var someInts: [Int] = []
print("someInts is of type [Int] with \(someInts.count) items.") // Prints "someInts is of type [Int] with 0 items."
---
output: someInts is of type [Int] with 0 items.
Note that by the constructor’s type, the value type of someInts
is inferred as [Int]
.
Alternatively, if the code context already provides type information, such as a function parameter or a constant/variable with a defined type, you can use an empty array literal to create an empty array, simply written as []
(a pair of empty square brackets):
someInts.append(3)
print("Now someInts is: \(someInts).")
someInts = []
print("someInts is now \(someInts), but still of type [Int].")
---
output: Now someInts is: [3].
someInts is now [], but still of type [Int].
Creating an Array with Default Values
The Array
type in Swift
also provides a constructor to create an array of a specific size with all values set to a default. Pass the number of items (count
) and the initial value (repeating
) of the appropriate type to the array constructor.
var threeDoubles = Array(repeating: 0.0, count: 3) // threeDoubles is a [Double] array, equivalent to [0.0, 0.0, 0.0]
print("threeDoubles is \(threeDoubles)")
---
output: threeDoubles is [0.0, 0.0, 0.0]
Creating an Array by Adding Two Arrays
You can use the addition operator +
to combine two existing arrays of the same type. The new array’s data type is inferred from the types of the two arrays.
var anotherThreeDoubles = Array(repeating: 2.5, count: 3) // anotherThreeDoubles is inferred as [Double], equivalent to [2.5, 2.5, 2.5]
var sixDoubles = threeDoubles + anotherThreeDoubles // sixDoubles is inferred as [Double], equivalent to [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
print("The value of sixDoubles is: \(sixDoubles)")
---
output: The value of sixDoubles is: [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
Constructing an Array from an Array Literal
You can use array literals to construct arrays, which is a simple way to create an array with one or more values. An array literal is a series of values separated by commas and enclosed in square brackets:
[value 1, value 2, value 3]
The following example creates an array called shoppingList
that stores String
values:
var shoppingList: [String] = ["Eggs", "Milk"] // shoppingList is constructed with two initial items
print("shoppingList is \(shoppingList)")
---
output: shoppingList is ["Eggs", "Milk"]
The shoppingList
variable is declared as “an array of String values,” written as [String]
. Since this array is restricted to only String
data, only String
types can be stored in it. Here, the shoppingList
array is constructed with two String
values (“Eggs” and “Milk”) defined by the array literal.
Note
The
shoppingList
array is declared as a variable (created withvar
) rather than a constant (created withlet
) because more items will be added to it later.
In the above example, the literal contains only two String
values, matching the array’s declaration (can only contain String
), so you can view this assignment as constructing shoppingList
with two initial items.
Thanks to Swift’s type inference, when constructing an array with a literal of the same value type, you don’t need to explicitly define the array’s type. The construction of shoppingList
can also be written as:
var shoppingLists = ["Eggs", "Milk"]
Since all values in the array literal are of the same type, Swift can infer that [String]
is the correct type for the shoppingList
variable.
Accessing and Modifying Arrays
You can access and modify arrays using their methods and properties, or by using subscript syntax.
You can use the array’s read-only property count
to get the number of items in the array:
print("The shopping list contains \(shoppingLists.count) items.")
---
output: The shopping list contains 2 items.
Use the Boolean property isEmpty
as a shorthand to check if the count
property is 0
:
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// Prints "The shopping list is not empty."
---
output: The shopping list is not empty.
You can also use the append(_:)
method to add a new item to the end of the array:
shoppingList.append("Flour") // shoppingList now has 3 items, someone might be making pancakes
print("shoppingList after adding 'Flour': \(shoppingList).")
---
output: shoppingList after adding 'Flour': ["Eggs", "Milk", "Flour"].
Additionally, you can use the addition assignment operator +=
to add items from another array of the same type to the end of the array.
shoppingList += ["Baking Powder"] // shoppingList now has four items
shoppingList += ["Chocolate Spread", "Chinese", "Butter"] // shoppingList now has seven items
You can directly use subscript syntax to access items in the array by placing the index in square brackets after the array name:
var firstItem = shoppingList[0]
print("The first item in shoppingList is: \(firstItem).")
---
output: The first item in shoppingList is: Eggs.
Note
The first item’s index in the array is 0, not 1. Array indices in Swift always start at zero.
You can also use subscripts to change the value at a valid index:
shoppingList[0] = "Six Eggs" // Now the first item in shoppingList is "Six Eggs" instead of "Eggs"
print("shoppingList after modification: \(shoppingList)")
---
output: shoppingList after modification: ["Six Eggs", "Milk", "Flour", "Baking Powder", "Chocolate Spread", "Chinese", "Butter"]
When using subscript syntax, the index must be valid. For example, trying to add an item at the end with shoppingList[shoppingList.count] = "Salt"
will cause a runtime error.
You can also use subscripts to change a range of values at once, even if the number of new values is different from the original. The following example replaces “Chocolate Spread”, “Chese”, and “Butter” with “Bananas” and “Apples”.
shoppingList[4...6] = ["Bananas", "Apples"] // shoppingList now has 6 items
print("shoppingList is now: \(shoppingList)")
// Use the array's `insert(_:at:)` method to add an item at a specific index:
shoppingList.insert("Maple Syrup", at: 0) // shoppingList now has 7 items
// Now the first item in the list is "Maple Syrup"
print("The first item in shopingList is now: \(shoppingList[0])")
// This `insert(_:at:)` call inserts a new item "Maple Syrup" at the beginning of the list, using 0 as the index.
---
output: shoppingList is now: ["Six Eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"]
The first item in shopingList is now: Maple Syrup
Similarly, you can use the remove(at:)
method to remove an item at a specific index. This method removes and returns the item at the specified index (you can ignore the returned value if not needed).
let mapleSyrup = shoppingList.remove(at: 0) // shoppingList now has 6 items, not including "Maple Syrup", constant mapleSyrup equals "Maple Syrup"
print("mapleSyrup equals: \(mapleSyrup), shoppingList equals: \(shoppingList).")
---
output: mapleSyrup equals: Maple Syrup, shoppingList equals: ["Six Eggs", "Milk", "Flour", "Baking Powder", "Bananas", "Apples"].
Note
Attempting to access or modify data using an out-of-bounds index will cause a runtime error. You can compare the index value with the array’s
count
property to check its validity before using it. Except whencount
is 0 (meaning the array is empty), the maximum index is alwayscount - 1
because arrays are zero-indexed.
After an item is removed, the gap is automatically filled, so the item at index 0
is now “Six eggs”.
firstItem = shoppingList[0] // firstItem is now "Six eggs"
print("The first item in shoppingList is now: \(firstItem)")
// If you only want to remove the last item, you can use the `removeLast()` method instead of `remove(at:)` to avoid needing the array's `count` property. Like the latter, the former also returns the removed item.
let apples = shoppingList.removeLast() // The last item is removed, shoppingList now has 5 items, not including "Apples", constant apples now equals "Apples"
print("Constant apples now equals: \(apples), shoppingList equals: \(shoppingList).")
// Similarly, there is a `removeFirst()` method to remove the first item directly.
let sixEggs = shoppingList.removeFirst()
---
output: The first item in shoppingList is now: Six Eggs
Constant apples now equals: Apples, shoppingList equals: ["Six Eggs", "Milk", "Flour", "Baking Powder", "Bananas"].
Iterating Over an Array
You can use a for-in
loop to iterate over all items in an array:
for item in shoppingList {
print(item) // Six eggs; Milk; Flour; Baking Powder; Bananas
}
---
output: Milk
Flour
Baking Powder
Bananas
If you need both the value and the index of each item, you can use the enumerated()
method to iterate over the array. enumerated()
returns a tuple of index and value. The index starts at zero and increases by one each time; if you enumerate the entire array, the indices and values will match up. You can decompose this tuple into temporary constants or variables for iteration:
for (index, value) in shoppingList.enumerated() {
print("Item \(String(index + 1)): \(value)") // Item 1: Milk; Item 2: Flour; Item 3: Baking Powder; Item 4: Bananas
}
---
output: Item 1: Milk
Item 2: Flour
Item 3: Baking Powder
Item 4: Bananas
Sets
Sets are used to store values of the same type but with no defined order. When the order of elements is not important or you want to ensure each element appears only once, use a set instead of an array.
Note
The
Set
type in Swift is bridged to theNSSet
class in Foundation.
Hash Values for Set Types
To be stored in a set, a type must be hashable, meaning it must provide a way to compute its hash value. A hash value is of type Int
, and equal objects must have the same hash value, e.g., if a == b
, then a.hashValue == b.hashValue
.
All of Swift’s basic types (such as String
, Int
, Double
, and Bool
) are hashable by default and can be used as set values or dictionary keys. Enum members without associated values are also hashable by default.
Note
You can use custom types as set values or dictionary keys, but you need to make your custom type conform to the
Hashable
protocol in the Swift standard library. Types conforming toHashable
must provide a readablehashValue
property of typeInt
. The value returned by the type’shashValue
property does not need to remain the same across different executions of the same program or between different programs.Since
Hashable
conforms toEquatable
, types conforming to it must also provide an implementation of the equality operator (==
). TheEquatable
protocol requires that the implementation of==
for any instances must be an equivalence relation. That is, for values a, b, and c, the implementation must satisfy:
- a == a (reflexivity)
- a == b implies b == a (symmetry)
- a == b && b == c implies a == c (transitivity)
Set Type Syntax
In Swift
, the set type is written as Set<Element>
, where Element
is the type allowed in the set. Unlike arrays, sets do not have an equivalent shorthand form.
Creating and Building an Empty Set
You can use constructor syntax to create an empty set of a specific type:
var letters = Set<Character>()
print("Letters is of type Set<Character> with \(letters.count) items.") // Prints "Letters is of type Set<Character> with 0 items."
---
output: Letters is of type Set<Character> with 0 items.
Note
By using the constructor, the type of the
letters
variable is inferred asSet<Character>
.
Additionally, if the context provides type information, such as a function parameter or a variable/constant with a known type, you can create an empty set using an empty array literal:
letters.insert("A") // letters now contains 1 value of type Character
print("Now Letters is: \(letters)")
letters = [] // letters is now an empty Set, but still of type Set<Character>
print("Now Letters is: \(letters)")
---
output: Now Letters is: ["A"]
Now Letters is: []
Creating a Set with an Array Literal
You can use an array literal to construct a set, which is a simplified way to specify one or more values as set elements.
The following example creates a set called favoriteGenres
to store String
values.
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] // favoriteGenres is constructed as a set with three initial values
The favoriteGenres
variable is declared as “a set of String values,” written as Set<String>
. Since this set is specified to store only String
values, it only allows String
types. Here, the favoriteGenres
variable has three initial String
values (“Rock”, “Classical”, “Hip hop”), written as an array literal.
Note
favoriteGenres
is declared as a variable (with thevar
keyword) rather than a constant (withlet
) because elements will be added or removed in later examples.
A set type cannot be inferred directly from an array literal, so the Set
type must be explicitly declared. However, thanks to Swift’s type inference, if you want to construct a set from an array literal and all elements are of the same type, you don’t need to write out the set’s specific type. The construction of FavoriteGenres
can be simplified as:
var FavoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
Since all elements in the array literal are of type String
, Swift can infer that Set<String>
is the correct type for the favoriteGenres
variable.
Accessing and Modifying a Set
You can access and modify a set using its properties and methods.
To get the number of elements in a set, use its read-only property count
:
print("I have \(FavoriteGenres.count) favorite music genres.") // Prints "I have 3 favorite music genres."
---
output: I have 3 favorite music genres.
Use the Boolean property isEmpty
as a shorthand to check if the count
property is 0:
if FavoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
} // Prints "I have particular music preferences."
---
output: I have particular music preferences.
You can add a new element to a set by calling its insert(_:)
method:
FavoriteGenres.insert("Jazz") // FavoriteGenres now contains 4 elements.
print("FavoriteGenres now contains \(FavoriteGenres.count) elements: \(FavoriteGenres)")
---
output: FavoriteGenres now contains 4 elements: ["Classical", "Jazz", "Hip hop", "Rock"]
You can remove an element from a set by calling its remove(_:)
method. If the element exists, it is removed and returned; if not, nil
is returned. You can also remove all elements with the removeAll()
method.
if let removeGenre = FavoriteGenres.remove("Rock") {
print("\(removeGenre)? I'm over it!")
} else {
print("I never much cared of that!")
} // Prints "Rock? I'm over it!"
---
output: Rock? I'm over it!
Use the contains(_:)
method to check if a set contains a specific value:
if FavoriteGenres.contains("Funk") {
print("I get up on the good foot.")
} else {
print("It's too funky in here.")
} // Prints "It's too funky in here."
---
output: It's too funky in here.
Iterating Over a Set
You can use a for-in
loop to iterate over all values in a set.
for genre in FavoriteGenres {
print("\(genre)")
} // Hip hop; // Classical; // Jazz unordered
---
output: Classical
Jazz
Hip hop
The Set
type in Swift has no defined order. To iterate over a set in a specific order, use the sorted()
method, which returns an ordered array with elements sorted using the <
operator.
for genre in FavoriteGenres.sorted() {
print("\(genre)")
} // Classical; // Hip hop; // Jazz ordered
---
output: Classical
Hip hop
Jazz
Set Operations
You can efficiently perform basic set operations, such as combining two sets, finding common elements, or determining if two sets are subsets, supersets, or disjoint.
Basic Set Operations
- Use the
intersection(_:)
method to create a new set with the common elements of two sets. - Use the
symmetricDifference(_:)
method to create a new set with elements not shared by two sets. - Use the
union(_:)
method to create a new set with all elements from both sets. - Use the
subtracting(_:)
method to create a new set with elements not in another set.
let oddDigits: Set = [1, 3, 5, 7, 9]
let evenDigits: Set = [0, 2, 4, 6, 8]
let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
print("Union: \(oddDigits.union(evenDigits).sorted())") // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print("InterSection: \(oddDigits.intersection(evenDigits).sorted())") // []
print("SubTracting: \(oddDigits.subtracting(singleDigitPrimeNumbers).sorted())") // [1, 9]
print("SymmetricDifference: \(oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted())") // [1, 2, 9]
---
output: Union: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
InterSection: []
SubTracting: [1, 9]
SymmetricDifference: [1, 2, 9]
Set Membership and Equality
- Use the equality operator
==
to check if two sets contain the same values. - Use the
isSubset(of:)
method to check if all values in one set are also contained in another set. - Use the
isSuperset(of:)
method to check if a set contains all values of another set. - Use the
isStrictSubset(of:)
orisStrictSuperset(of:)
methods to check if a set is a strict subset or superset of another set and the two sets are not equal. - Use the
isDisjoint(with:)
method to check if two sets have no values in common (are disjoint).
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]
print("IsSubset? \(houseAnimals.isSubset(of: farmAnimals))") // Prints "IsSubset? true"
print("IsSuperset? \(farmAnimals.isSuperset(of: houseAnimals))") // Prints "IsSuperset? true"
print("IsDisjoint? \(farmAnimals.isDisjoint(with: cityAnimals))") // Prints "IsDisjoint? true"
---
output: IsSubset? true
IsSuperset? true
IsDisjoint? true
Dictionaries
A dictionary is an unordered collection that stores associations between keys and values, where all keys must be of the same type and all values must be of the same type. Each value is associated with a unique key, which acts as the identifier for that value in the dictionary. Unlike arrays, dictionary items have no specific order. Use a dictionary when you need to access data by identifier (key), similar to how you look up definitions in a real-world dictionary.
Note
Swift’s
Dictionary
type is bridged to theNSDictionary
class in Foundation.
Shorthand Syntax for Dictionary Types
Swift dictionaries are defined as Dictionary<Key, Value>
, where Key
is a type that can be used as a key in the dictionary, and Value
is the type of values stored for those keys.
Note
A dictionary’s Key type must conform to the
Hashable
protocol, just like the value type for a Set.
You can also use the shorthand [Key: Value]
to represent a dictionary type. Both forms are functionally identical, but the latter is preferred and will be used throughout this tutorial.
Creating an Empty Dictionary
Like arrays, you can use constructor syntax to create an empty dictionary with a specific type:
var namesOfInteger: Dictionary<Int, String> = Dictionary<Int, String>() // Using Dictionary<Key, Value> to define a dictionary
print("Using Dictionary<Key, Value> to define a dictionary: \(namesOfInteger)")
var namesOfIntegers: [Int: String] = [:] // Shorthand syntax, preferred!
print("Shorthand syntax, preferred: \(namesOfIntegers)")
---
output: Using Dictionary<Key, Value> to define a dictionary: [:]
Shorthand syntax, preferred: [:]
This example creates an empty dictionary of type [Int: String]
to store English names for integers. Its keys are of type Int
, and its values are of type String
.
If the context already provides type information, you can use an empty dictionary literal to create an empty dictionary, written as [:]
(a pair of square brackets with a colon inside):
namesOfIntegers[16] = "sixteen" // namesOfIntegers now contains one key-value pair
namesOfIntegers = [:] // namesOfIntegers is now an empty [Int: String] dictionary again
Creating a Dictionary with a Dictionary Literal
You can use a dictionary literal to construct a dictionary, which is similar in syntax to array literals. A dictionary literal is a quick way to write one or more key-value pairs as a Dictionary
collection.
A key-value pair is a combination of a key and a value, separated by a colon in the dictionary literal. These key-value pairs form a list, separated by commas and enclosed in square brackets:
// [key 1: value 1, key 2: value 2, key 3: value 3]
The following example creates a dictionary storing the names of international airports. In this dictionary, the keys are three-letter IATA codes, and the values are airport names:
var airposts: [String: String] = ["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX":"Beijing Daxing", "SHA":"Shanghao Hongqiao"]
print("China Main Airpots: \(airposts)")
---
output: China Main Airpots: ["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX": "Beijing Daxing", "SHA": "Shanghao Hongqiao"]
The airports
dictionary is declared as a [String: String]
type, meaning both its keys and values are of type String
.
Note
The
airports
dictionary is declared as a variable (withvar
) rather than a constant (withlet
) because more airports will be added to it later.
The airports
dictionary is initialized with a dictionary literal containing four key-value pairs. These match the declared type of the airports
variable (a dictionary with only String
keys and values), so this assignment is a way to construct the airports
dictionary with four initial items.
As with arrays, when constructing a dictionary with a literal where all keys and values are of the same type, you don’t need to specify the dictionary’s type. The airports
dictionary can also be defined in this shorter way:
var chinaAirports = ["HFE": "Hefei Luogang", "NKG": "Nanjing Lukou", "PKX":"Beijing Daxing", "SHA":"Shanghao Hongqiao"]
Since all keys and values in this statement are of the same type, Swift can infer that [String: String]
is the correct type for the airports
dictionary.
Accessing and Modifying a Dictionary
You can access and modify a dictionary using its methods and properties, or by using subscript syntax.
As with arrays, you can use the dictionary’s read-only property count
to get the number of items:
print("The dictionary of chinaAirports contains \(chinaAirports.count) items.") // Prints "The dictionary of chinaAirports contains 4 items."
---
output: The dictionary of chinaAirports contains 4 items.
Use the Boolean property isEmpty
as a shorthand to check if the count
property is 0:
if chinaAirports.isEmpty {
print("The chinaAirports dictionary is empty.")
} else {
print("The chinaAirports dictionary is not empty.")
} // Prints "The chinaAirports dictionary is not empty."
---
output: The chinaAirports dictionary is not empty.
You can use subscript syntax to add a new item to a dictionary by using a key of the appropriate type as the subscript index and assigning a new value of the appropriate type:
airposts["XIY"] = "Xi'an" // The airports dictionary now has five items
print(airposts)
---
output: ["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX": "Beijing Daxing", "XIY": "Xi\'an", "SHA": "Shanghao Hongqiao"]
You can also use subscript syntax to change the value for a specific key:
airposts["XIY"] = "Xi'an Xianyang" // The value for "XIY" is changed to "Xi'an Xianyang"
print(airposts)
---
output: ["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX": "Beijing Daxing", "XIY": "Xi\'an Xianyang", "SHA": "Shanghao Hongqiao"]
As an alternative to subscript syntax, the dictionary’s updateValue(_:forKey:)
method can set or update the value for a specific key. Like the subscript example above, updateValue(_:forKey:)
sets a new value if the key does not exist or updates the existing value if it does. Unlike the subscript method, updateValue(_:forKey:)
returns the original value before the update, allowing you to check if the update was successful.
The updateValue(_:forKey:)
method returns an optional of the value type. For example, for a dictionary storing String
values, this function returns a String?
(optional String). If a value existed before the update, the optional contains the old value; otherwise, it is nil
:
if let oldValue = airposts.updateValue("Hefei Xinqiao", forKey: "HFE") {
print("The old value for HFE was \(oldValue).")
} // Prints "The old value for HFE was Hefei Xinqiao."
---
output: The old value for HFE was Hefei Xinqiao.
You can also use subscript syntax to retrieve the value for a specific key in a dictionary. Since the requested key might not have a corresponding value, dictionary subscript access returns an optional of the value type. If the dictionary contains a value for the requested key, the subscript returns an optional containing the value; otherwise, it returns nil
:
if let airportName = airposts["HFE"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
} // Prints "The name of the airport is Hefei Xinqiao."
---
output: The name of the airport is Hefei Xinqiao.
You can also use subscript syntax to remove a key-value pair from a dictionary by assigning nil
to the value for a key:
airposts["CAN"] = "Guangzhou Baoan" // Baoan airport is in Shenzhen, so remove it
print(airposts)
airposts["CAN"] = nil // CAN is now removed
print(airposts)
---
output: ["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX": "Beijing Daxing", "XIY": "Xi\'an Xianyang", "CAN": "Guangzhou Baoan", "SHA": "Shanghao Hongqiao"]
["HFE": "Hefei Xinqiao", "NKG": "Nanjing Lukou", "PKX": "Beijing Daxing", "XIY": "Xi\'an Xianyang", "SHA": "Shanghao Hongqiao"]
Additionally, the removeValue(forKey:)
method can be used to remove a key-value pair from a dictionary. If the key-value pair exists, this method removes it and returns the removed value; if not, it returns nil
:
if let removeValue = airposts.removeValue(forKey: "NKG") {
print("The removed airport's name is \(removeValue).")
} else {
print("The airports dictionary does not contain a value for NKG.")
} // Prints "The removed airport's name is Nanjing Lukou."
---
output: The removed airport's name is Nanjing Lukou.
Iterating Over a Dictionary
You can use a for-in
loop to iterate over the key-value pairs in a dictionary. Each item in the dictionary is returned as a (Key, Value)
tuple, which you can decompose into temporary constants or variables.
for (airportCode, airportName) in airposts {
print("\(airportCode): \(airportName)")
} // HFE: Hefei Xinqiao; // PKX: Beijing Daxing; //SHA: Shanghao Hongqiao; // XIY: Xi'an Xianyang
---
output: HFE: Hefei Xinqiao
PKX: Beijing Daxing
XIY: Xi'an Xianyang
SHA: Shanghao Hongqiao
By accessing the keys
or values
properties, you can iterate over the keys or values of a dictionary:
for airportCode in airposts.keys {
print("Airport code: \(airportCode)")
}
for airportName in airposts.values {
print("Airport name: \(airportName)")
}
---
output: Airport code: HFE
Airport code: PKX
Airport code: XIY
Airport code: SHA
Airport name: Hefei Xinqiao
Airport name: Beijing Daxing
Airport name: Xi'an Xianyang
Airport name: Shanghao Hongqiao
If you need to use the key set or value set of a dictionary as a parameter for an API that accepts an Array
instance, you can directly use the keys
or values
property to construct a new array.
let airportCodes = [String](airposts.keys) // airportCodes is ["HFE", "PKX", "SHA", "XIY"]
print(airportCodes)
let airportNames = [String](airposts.values) // airportNames is ["Hefei Xinqiao", "Beijing Daxing", "Shanghai Hongqiao", "Xi'an Xianyang"]
print(airportNames)
---
output: ["HFE", "PKX", "XIY", "SHA"]
["Hefei Xinqiao", "Beijing Daxing", "Xi\'an Xianyang", "Shanghao Hongqiao"]
Swift’s Dictionary
is an unordered collection type. To iterate over the keys or values of a dictionary in a specific order, use the sorted()
method on the dictionary’s keys
or values
property.