Collection Types
Swift provides three primary collection types, known as arrays, sets, and dictionaries, for storing collections of values. Swift are always clear about the types of values and keys that they can store. This means that you cannot insert a value of the wrong type into a collection by mistake.
- Arrays are ordered collections of values.
- Sets are unordered collections of unique values.
- Dictionaries are unordered collections of key-value associations
Mutability of Collections
Use let
or var
It is good practice to create immutable collections in all cases where the collection does not need to change.
Arrays
An array stores values of the same type in an ordered list. The same value can appear in an array multiple times at different positions.
Array Type Shorthand Syntax
full as Array<Element>
shorthand form as[Element]
Create Array
Empty Array
1 | var someInts = [Int]() |
Array with a Default Value
1 | var threeDoubles = Array(repeating: 0.0, count: 3) |
Adding Two Arrays Together
1 | var anotherThreeDoubles = Array(repeating: 2.5, count: 3) |
Array Literal
1 | var shoppingList: [String] = ["Eggs", "Milk"] |
Array count
the largest valid index in an array will always be count - 1, because arrays are indexed from zero.
Find out the number of items
1 | print("The shopping list contains \(shoppingList.count) items.") |
Checking count
1 | if shoppingList.isEmpty { |
Add a new item
1 | // add a new item to the end |
Subscript syntax
Retrieve a value
You can’t use subscript syntax to append a new item to the end of an array.
1 | var firstItem = shoppingList[0] |
Change an existing value
1 | shoppingList[0] = "Six eggs" |
Change a range of values
1 | shoppingList[4...6] = ["Bananas", "Apples"] |
Insert an item
1 | shoppingList.insert("Maple Syrup", at: 0) |
Remove an item
returns the removed item
1 | let mapleSyrup = shoppingList.remove(at: 0) |
Iterating Over an Array
Only value
1 | for item in shoppingList { |
Integer index with value
1 | for (index, value) in shoppingList.enumerated() { |
Sets
A set stores distinct values of the same type in a collection with no defined ordering.
When to use
- You can use a set instead of an array when the order of items is not important,
- or when you need to ensure that an item only appears once.
Hash Values for Set Types
- A type must be hashable in order to be stored in a set—that is, the type must provide a way to compute a hash value for itself.
- All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default
- Enumeration case values without associated values are also hashable by default.
- custom types:conform to the
Hashable
protocol from Swift’s standard library ( gettable Int property called hashValue) - Hashable protocol conforms to
Equatable
, conforming types must also provide an implementation of the equals operator (==).
Set Type Syntax
Set<Element>
Creating and Initializing an Empty Set
1 | var letters = Set<Character>() |
Creating a Set with an Array Literal
1 | var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] |
A set type cannot be inferred from an array literal alone, so the type Set must be explicitly declared.
1 | var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"] |
Accessing and Modifying a Set
Find out the number of items
1 | print("I have \(favoriteGenres.count) favorite music genres.") |
Checking isEmpty
1 | if favoriteGenres.isEmpty { |
Add a new item
1 | favoriteGenres.insert("Jazz") |
Remove item
all items in a set can be removed with its removeAll()
method.
1 | // return nil or removed value |
Check ifcontains
1 | if favoriteGenres.contains("Funk") { |
Iterating Over a Set
1 | for genre in favoriteGenres { |
Swift’s Set type does not have a defined ordering. To iterate over the values of a set in a specific order, use the sorted() method, which returns the set’s elements as an array sorted using the < operator.
1 | for genre in favoriteGenres.sorted() { |
Performing Set Operations
Fundamental Set Operations
此处应有图
1 | let oddDigits: Set = [1, 3, 5, 7, 9] |
Set Membership and Equality
此处应有图
1 | let houseAnimals: Set = ["🐶", "🐱"] |
Dictionaries
Dictionary Type Shorthand Syntax
Dictionary<Key, Value>
shorthand form as [Key: Value]
- A dictionary Key type must conform to the Hashable protocol, like a set’s value type
- All of Swift’s basic types (such as String, Int, Double, and Bool) are hashable by default
- Enumeration case values without associated values are also hashable by default.
- custom types:conform to the
Hashable
protocol from Swift’s standard library ( gettable Int property called hashValue) - Hashable protocol conforms to
Equatable
, conforming types must also provide an implementation of the equals operator (==).
Creating an Empty Dictionary
1 | var namesOfIntegers = [Int: String]() |
Creating a Dictionary with a Dictionary Literal
1 | var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] |
Dictionary count
Find out the number of items
1 | print("The airports dictionary contains \(airports.count) items.") |
Checking isEmpty
1 | if airports.isEmpty { |
Subscript
Add a new item
1 | airports["LHR"] = "London" |
Retrieve a value
a dictionary’s subscript returns an optional value (value or nil)
1 | if let airportName = airports["DUB"] { |
Remove a key-value pair
assigning a value of nil for that key
1 | airports["APL"] = "Apple International" |
Accessing method
Set new value or Change old value
the method returns a value of type String?, or “optional String”. This optional value contains the old value for that key if one existed before the update, or nil if no value existed
1 | if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") { |
Remove a key-value pair
returns the removed value, or returns nil
1 | if let removedValue = airports.removeValue(forKey: "DUB") { |
Iterating Over a Dictionary
Swift’s Dictionary type does not have a defined ordering. To iterate over the keys or values of a dictionary in a specific order, use the sorted()
method on its keys or values property.
1 | for (airportCode, airportName) in airports { |
Accessing Key and Value
retrieve an iterable collection of a dictionary’s keys or values
1 | for airportCode in airports.keys { |
key or value become array
1 | let airportCodes = [String](airports.keys) |