Skip to content

Instantly share code, notes, and snippets.

@tombaranowicz
Created December 12, 2019 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tombaranowicz/f6ca0f176a14864bb84da4cd0161207f to your computer and use it in GitHub Desktop.
Save tombaranowicz/f6ca0f176a14864bb84da4cd0161207f to your computer and use it in GitHub Desktop.
Swift Collections - Set
//SETS
//CREATE
//immutable - using array literal
let mazdas: Set = ["2", "3", "3", "6", "CX-3", "CX-5", "CX-9", "MX-5", "CX-30"]
let oldMazdas: Set<String>
oldMazdas = ["323", "626"]
//mutable - using initialiser syntax
var europeanMazdas = Set<String>(["2", "3", "3", "6", "CX-3", "CX-5", "CX-30"])
var americanMazdas: Set = ["2", "3", "3", "6", "CX-3", "CX-5", "CX-9", "MX-5", "MX-5"]
//check if set is empty
mazdas.isEmpty
//check amount of elements in set
mazdas.count
//ADD DATA
europeanMazdas.insert("MX-5")
//check if element already exists in set
europeanMazdas.contains("MX-5")
//ITERATE
//for model in mazdas {
// print(model.uppercased())
//}
//REMOVE DATA
//europeanMazdas.remove("MX-5")
//remove all elements at once
//europeanMazdas.removeAll()
//SET ALGEBRA https://en.wikipedia.org/wiki/Algebra_of_sets
//SUBTRACT (remove elements of one set, from another one)
let mazdasUnavailableInEurope = mazdas.subtracting(europeanMazdas)
//print(mazdasUnavailableInEurope)
//INTERSECT (returns common objects, which are in both sets)
let globalMazdaModels = europeanMazdas.intersection(americanMazdas)
//print(globalMazdaModels)
//UNION (returns all objects from both sets, without duplicates)
let allMazdas = americanMazdas.union(europeanMazdas)
print(allMazdas)
//SUBSET (checks if all elements of one set are also in another)
europeanMazdas.isSubset(of: mazdas)
europeanMazdas.isSubset(of: americanMazdas)
mazdas.isSubset(of: mazdas) //returns true if both sets contain exactly same elements
mazdas.isStrictSubset(of: mazdas) //returns false if both sets contain exactly same elements
//SUPERSET (checks if one set contains all elements of another)
mazdas.isSuperset(of: europeanMazdas) //returns true if both sets contain exactly same elements
mazdas.isStrictSuperset(of: europeanMazdas) //returns false if both sets contain exactly same elements
//DISJOINT (checks if there is no overlap between sets)
let tesla: Set = ["S", "X", "Y"]
tesla.isDisjoint(with: mazdas)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment