In Swift, a set is a collection of unordered unique values that are not duplicated. Sets are different from arrays. While arrays can contain duplicates, a
We can create a collection of sets in many ways. We can literarily create a set and we can create it by specifying the type of set.
Note: When you print a set, the element order is different. This is because a set has no particular order.
setName: Set = [elements] // specify by type setName: Set<datatype> = [elements]
setName: This is the name of the set.
elements: This represents the elements of the set.
datatype: This is used to specify the data type of the set. That is, the type of data that the set can have.
Set object is returned.
import Swift // create sets literally let lectureId: Set = [023, 055, 034, 065, 134] let userId: Set = ["24sd2", "s44ew", "34ffs"] // create sets by types let evenNumbers: Set<Int> = [2, 4, 6, 8, 10] let isStudentNice: Set<Bool> = [false, true, true, false, false] let prices: Set<Double> = [24.32, 45.32, 40.00, 1.45] let names: Set<String> = ["Theodore", "Ruth", "Chichi", "Amaka"] // print the sets to the console print(lectureId) print(userId) print(evenNumbers) print(isStudentNice) print(prices) print(names)
View all Courses