Chapter 7: Arrays, Dictionaries, and Sets
大綱
Creating arrays
Accessing elements
Using properties and methods
Using subscripting
Checking for an element
Modifying array
Appending elements
Inserting elements
Removing elements
Updating elements
Moving elements
Iterating through an array
Creating dictionaries
Accessing elements
Using properties and methods
Using subscripting
Modifying dictionaries
Adding pairs
Updating values
Removing pairs
Iterating through dictionaries
Creating sets
Set literals
Accessing elements
Adding and removing elements
Running time for set operations
Mutable versus immutable collections
If the collection doesn’t need to change after you’ve created it, you should make it immutable by declaring it as a constant with let.
if you need to add, remove or update values in the collection, then you should create a mutable collection by declaring it as a variable with var.
Arrays
Running time for array operations
Accessing elements: O(1)
Inserting elements:
add to the beginning of the array: O(n).
add to the middle of the array: O(n).
add to the end of the array using append and there’s room: O(1).
Deleting elements: O(1)
Searching for an element: O(n)
Dictionaries
Running time for dictionary operations
While all of these running times compare favorably to arrays, remember that you lose order information when using dictionaries..
Accessing elements: O(1)
Inserting elements: O(1)
Deleting elements: O(1)
Searching for an element: O(1)
Sets
Key points
Sets
Are unordered collections of unique values of the same type.
Are most useful when you need to know whether something is included in the collection or not.
Dictionaries
Are unordered collections of key-value pairs.
The keys are all of the same type, and the values are all of the same type.
Use subscripting to get values and to add, update or remove pairs.
If a key is not in a dictionary, lookup returns nil.
The key of a dictionary must be a type that conforms to the Hashable protocol.
Basic Swift types such as String, Int, Double are Hashable out of the box.
Arrays:
Are ordered collections of values of the same type.
Use subscripting, or one of the many properties and methods, to access and update elements.
Be wary of accessing an index that’s out of bounds.
Last updated