Swift several function records on set calculation

Intersect, symmetricDifference, Union, Subtract

First, concept introduction
Intersection (_ :) creates a new collection that contains only two common values. SymmetricDifference (_ :) creates a new set whose value sets are in both sets but cannot exist at the same time. (nonintersection) union (_ :) creates a new set containing all the values in both sets. Subtracting (_ :) creates a new set whose value is not in the specified set. (complement)Copy the code
Take an example

Let’s create a new playground.

["1","2","3"] // Print (list1. Intersection (list2)) / / neither list1, nor list2 in print (list1. SymmetricDifference (list2)) / / list1 and list2 added up to all of the data, Print (list1.union(list2)) // Belong to list1 but not belong to list2 print(list1.subtracting(list2))Copy the code
In addition, there are several other methods of Set:
"==" is used to determine whether two sets contain all the same elements and "isSubset(of:)" is used to determine whether the former is a subset of the latter. The "isSuperset(of:)" method is used to determine whether the latter is a subset of the former. Determine whether a subset (subset and unequal) is true by "isStrictSubset(of:)" or "isStrictSuperset(of:)". The "isDisjoint(with:)" method is used to determine whether two sets have the same elements, that is, whether two sets have an intersection.Copy the code
     let s1: Set = ["1", "2"]
     let s2: Set = ["1", "2", "3", "4", "5"]
     let s3: Set = ["4", "5"]
        
     s1.isSubset(of: s2)
     // true
     s2.isSuperset(of: s1)
     // true
     3.isDisjoint(with: s2)
Copy the code
Four, other types of conversion is also applicable

Currently in Swift, the above function can only be used for collection classes (Set < Element >), but if we are using other collection types such as arrays ([int]), dictionaries ([int: String]).

We need to convert the type as follows:

    let list1:[String] = ["1","2","3"]
    let list2:[String] = ["2","3","4"]
    let s1 = Set(list1)
    let s2 = Set(list2)
    
    print(s1.intersection(s2))
    print(s1.symmetricDifference(s2))
    print(s1.union(s2))
    print(s1.subtracting(s2))
Copy the code

Sometimes, when you need to do something similar with data, you can simply do this with collections.