Performing operations on sets

suggest change

Common values from both sets:

You can use intersection(_:) to create a new set containing the values common to both sets. Swift 2 named this method intersect. Set order is not guaranteed; the comments show membership only.

let favoriteColors: Set = ["Red", "Blue", "Green"]
let newColors: Set = ["Purple", "Orange", "Green"]

let intersect = favoriteColors.intersection(newColors) // a AND b
// intersect = {"Green"}

All values from each set:

You can use the union(_:) method to create a new set containing all the unique values from each set.

let union = favoriteColors.union(newColors) // a OR b
// union = {"Red", "Purple", "Green", "Orange", "Blue"}

Notice how the value “Green” only appears once in the new set.

Values that don’t exist in both sets:

You can use symmetricDifference(_:) to create a new set containing the values that are in one set but not both. Swift 2 named this method exclusiveOr.

let exclusiveOr = favoriteColors.symmetricDifference(newColors) // a XOR b
// exclusiveOr = {"Red", "Purple", "Orange", "Blue"}

Notice how the value “Green” doesn’t appear in the new set, since it was in both sets.

Values that are not in a set:

You can use subtracting(_:) to create a new set containing the values from the first set that are not in the second. Swift 2 named this method subtract. The mutating form is still subtract(_:).

let subtract = favoriteColors.subtracting(newColors) // a - (a AND b)
// subtract = {"Blue", "Red"}

Notice how the value “Green” doesn’t appear in the new set, since it was also in the second set.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents