Swift collection Set and common methods
1. Create Set Collection
// Create Setvar set: Set<Int> = [1, 2, 3] var set2 = Set(arrayLiteral: 1, 2, 3)
2. Get elements
// set gets the minimum value() // Get the first element, in a different orderset[] // Get elements through subscripts, you can only move backwards, not forwards// Get the second elementset[(after: )] // Get several elements after a certain subscriptset[(, offsetBy: 2)]
3. Common methods
// Get the number of elements //Judge empty setif { print("set is empty") } // Determine whether the set contains an elementif ((3)) { print("set contains 3") } // Insert(0) // Remove(2) () // Remove elements in the specified position and need to use ! Unpacking, you get the Optional type. If you remove non-existent elements, EXC_BAD_INSTRUCTION(at: (of: 1)!) () var setStr1: Set<String> = ["1", "2", "3", "4"] var setStr2: Set<String> = ["1", "2", "5", "6"] // Set to get the intersection(setStr2) // {"2", "1"} // Set to get the complement of the intersection(setStr2) // {"4", "5", "3", "6"} // Set to collect and combine(setStr2) // {"2", "3", "1", "4", "6", "5"} // Set takes the relative complement (difference set), (B), that is, take the element set that belongs to A but not B(setStr2) // {"3", "4"} var eqSet1: Set<Int> = [1, 2, 3] var eqSet2: Set<Int> = [3, 1, 2] //Judge Set set equalityif eqSet1 == eqSet2 { print("When all elements in a collection are equal, the two sets are equal, and have nothing to do with the order of the elements") } let set3: Set = [0, 1] let set4: Set = [0, 1, 2] //Judge subset(of: set4) // set3 is a subset of set4, true(of: set4) // set3 is a true subset of set4, true // Judgment superset(of: set3) // set4 is a superset of set3, true(of: set3) // set4 is the true superset of set3, true
4. Set traversal
// traverse elementsfor ele in set4 { print(ele) } // traverse the enumeration of the collectionfor ele in () { print(ele) } // Subscript traversalfor index in { print(set4[index]) } //Sort from small to large and then go throughfor ele in (by: <) { print(ele) }
GitHub source code:
This is the end of this article about the detailed explanation and summary of Swift Set collections and common methods. For more related contents of Swift Set collections, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!