Variables

Sets in Swift

Used to store values like an array and ensure there are no duplicates.


Syntax
var setName = Set<dataType>()
setName.insert(value) //insert a value

//type inference optional if you know they're all the same type
var setName: Set<dataType> = [value1, value2, ...]

//remove item from set, returns an optional of the item's type
let removedItem = setName.remove("itemToRemove")

Notes

The data type for the set must be hashable.

The order of a set is not guaranteed.

Array methods like count and isEmpty also exist for Sets. In addition, set operations can be done on sets (intersect, exclusiveOr, union, subtract).

An item can be removed from a set using the .remove(value) method. It returns an optional type.


Example
var integers: Set<Int> = [1, 2, 3, 4, 5]
integers.insert(6)

< Dictionaries   |   Enumerations >

© 2019 SyntaxDB. All Rights Reserved.