Swift provides three main collection types, called arrays, collections, and dictionaries, for storing collections of values. An array is an ordered collection of values. A set is an unordered set of unique values. A dictionary is an unordered collection of key-value associations. Swift’s array, collection, and dictionary types are implemented as generic collections. If you create an array, collection, or dictionary and assign it to a variable, the created collection will be mutable. This means that you can change (or mutate) a collection after it is created by adding, deleting, or changing items in the collection. If an array, collection, or dictionary is assigned to a constant, the collection is immutable, and its size and contents cannot be changed.

It is good practice to create immutable collections in all cases where you do not need to change the collection. Doing so makes it easier for you to reason through your code and enables the Swift compiler to optimize the performance of the collections you create.

An array of

A collection of values of the same type, ordered and repeatable. Swift’s Array type Bridges to object-C’s NSArray class. Array creation is written entirely as Array< type a> and is used to store a collection of elements related to type A, which we can also abbreviate to [type a].

  1. Build array
Var emptyArray:[Int] = [] var emptyArray:[Int] = [] var emptyArray:[Int] = [] var emptyArray:[Int] = [] var emptyArray:[Int] = [] var emptyArray:[Int] = [ OneArray = Array(repeating: 0.0, count: 3) var twoArray = Array(repeating: 2.5, count: 3) 3) print(oneArray+twoArray) // print(oneArray+twoArray) 2.5] / / / use literal creating arrays var threeArray: [String] = [" word ", "face", "quantity"] / / / can be abbreviated var threeArray1 = [" word ", "face", "quantity"]Copy the code
  1. Modify and access arrays
Print (" threeArray1 has \(threearray1.count) elements ") print(threeArray1 has \(threearray1.count) elements" // add element threearray1.append (".") // append one or more items to the array using the addition assignment operator (+=) threeArray1 += threeArray print(threeArray1) // [" word ", "Face "," measure ", ".", "word "," face ", Print (threeArray1[0]); print(threeArray1[0]); print(threeArray1]); "Face", "quantity", ". ", "words", "face", "quantity"] / / / replace a range of values threeArray1 [0, 3]... = (" 2 ") print (threeArray1) / / / "2", "words", "face", ThreeArray1. Insert ("AAA", at: 0) print (threeArray1) / / / "AAA", "2", "words", "face", "quantity"] / / / delete the corresponding subscript elements threeArray1. Remove (at: 0) print (threeArray1) / / / "2", "words", "face", "quantity"] / / / delete the first element threeArray1. RemoveFirst () print (threeArray1) / / [" word ", "face", RemoveLast () print(threeArray1) For item in threeArray1 {print(item) // word // face} /* If you need the integer index of each item and its value, use enumerated() method to iterate over the array. For each item in the array, the enumerated() method returns a tuple of integers and items. **/ for (index,ietm) in threearray1.enumerated () {print("threeArray1 \(index) element \(ietm)") // threeArray1 \(index) element \(ietm)") // ThreeArray1 the first element is the face}Copy the code

A collection of

A collection is unordered and the elements cannot be repeated. A collection can be used when the order of the elements is not important and the values of the elements must be unique.

The hash value of the collection type

A type must be hashed in order to be stored in a collection — that is, the type must provide a way to calculate the hash value for itself. The hash value is an Int value, which is the same for all objects in the equality comparison, so if a == b, then the hash value of a is equal to the hash value of B.

grammar

The type of a Swift collection is written as Set< Element >, where Element is the type that the collection is allowed to store. Unlike arrays, there is no equivalent shorthand for collections.

var set:Set = Set<Element: Hashable>()
Copy the code

Initialize set

Use a specific type to create an empty collection

var set:Set = Set<Int>()
set.insert(1)
Copy the code

Literal to create a collection

You can also use array literals to initialize a collection as a shorthand for writing one or more values to a collection.

Var set: set <String> = [" word ", "face "," quantity "]Copy the code

You cannot infer a collection type from array literals alone, so you must explicitly declare the type Set. However, because of Swift’s type inference, you don’t have to write the type of the collection element if you initialize it with an array literal that contains values of only one type.

Var set: set = [" ", ""," "]Copy the code

Using the collection

Collection of common methods

Var set: set = [" ", ""," "] print("set num \(set.count)") //set num 3 // Set. IsEmpty {print (" collection is not null ")} / / / set insert element set. The insert (". ") print (set) / / [" face ", ""," words ", "Quantity"] / / / delete an element set. Remove (". ") print (set) / / [" word ", "quantity", Set.removeall () print(set) // [] // Determine whether set.contains("22") // falseCopy the code

Traverse the collection

Var numberSet:Set = ["1","22","333"] for num in numberSet {print(num) //1 //333 //22} for num in numberSet = ["1","22","333"] for num in numberSet {print(num) //1 //333 //22 numberSet.sorted() { print(num) // 1 // 22 // 333 }Copy the code

Set operations

We can combine the two sets and determine which values are in common. Or whether set A contains all or part of set B, or no identical elements.

1. Basic set operations

Returns the same value intersection(_:) of the set A and B

Var A: Set = [1, 2, 3, 4, 5] var B: Set =,6,7,8,9 [5] print (Anderson ntersection (B)) / / [5]Copy the code

Gets the value symmetricDifference(_:) for two collections that are different

Var A: Set = [1, 2, 3, 4, 5] var B: Set =,6,7,8,9 [5] print (A.s ymmetricDifference (B)) / / [1, 4, 3, 9, 8, 7, 6, 2)Copy the code

Use the union(_:) method to create a new set containing all the values from both sets.

Var A: Set = [1, 2, 3, 4, 5] var B: Set =,6,7,8,9 [5] print (A.u nion (B)) / / [4, 9, 7, 3, 6, 8, 1, 5, 2)Copy the code

Gets a collection subtracting(_:) that does not contain the specified collection

Var A: Set = [1, 2, 3, 4, 5] var B: Set =,6,7,8,9 [5] print (A.s ubtracting (B)) / / [1, 2, 3, 4]Copy the code

2. Inclusion relationships between sets

Determine whether the sets are equal

Let houseAnimals: Set = [" 🐶 ", "🐱"] let farmAnimals: Set = [" 🐮 ", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] if houseAnimals == farmAnimals {print(" contains all the same values ")} else {print(" does not contain all the same values ")} // Does not contain all the same valuesCopy the code

The isSubset(of:) method is used to determine whether all the values of a set are included in the specified set.

Let houseAnimals: Set = [" 🐶 ", "🐱"] let farmAnimals: Set = [" 🐮 ", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] subset (of: farmAnimals) // trueCopy the code

Determines whether all isSuperset(of:) elements of the specified collection are contained

Let houseAnimals: Set = [" 🐶 ", "🐱"] let farmAnimals: Set = [" 🐮 ", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] Farmanimals.issuperset (of: houseAnimals) // trueCopy the code

Determine whether it is a subset or superset

Let houseAnimals: Set = [" 🐶 ", "🐱"] let farmAnimals: Set = [" 🐮 ", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = [" 🐦 🐭 ", ""] farmAnimals. IsStrictSuperset (of: HouseAnimals) / / true farmAnimals is a superset of houseAnimals houseAnimals. IsStrictSubset (of: FarmAnimals) / / true houseAnimals is a subset of the set of farmAnimals cityAnimals isStrictSubset (of: // False cityAnimals is not a subset of farmAnimalsCopy the code

Determine if there are no common values

Let houseAnimals: Set = [" 🐶 ", "🐱"] let farmAnimals: Set = [" 🐮 ", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals. IsDisjoint (with: farmAnimals) // false houseAnimals. cityAnimals) // trueCopy the code

The dictionary

Dictionaries store associations between keys of the same type and values of the same type in collections, in no defined order. Each value is associated with a unique key that acts as the identifier for the value in the dictionary.

grammar

The Swift Dictionary is written to Dictionary<Key, Value>, where Key is the type of Value that can be used as a Dictionary Key, and Value is the type of Value that the Dictionary stores for those keys.

var dic:Dictionary = Dictionary<Key: Hashable, Any>()
Copy the code

Initializing a dictionary

var dic:Dictionary = Dictionary<String, Any>()
Copy the code