A set is a collection of unique elements without duplicates. However, we can create a set with duplicate elements. But the magic is that Swift will know that the duplicate elements ought to be one. Hence, it will remove all duplicates.
let setName: Set = [duplicateElements] // by specifying type of set let setName: Set<type> = [duplicateElements]
setName
: This is the name of the set we want to create.duplicateElements
: This represents the elements of the sets that are duplicates.type
: This is the type of the set. It could be Int
, String
, and so on.The value returned after creating a set with duplicate elements will be a set that discards all duplicates.
import Swift // create duplicate set collections let lectureId: Set = [023, 023, 055, 034, 065,065, 134] let userId: Set = ["24sd2", "24sd2", "24sd2", "24sd2"] let evenNumbers: Set<Int> = [2, 4, 6, 8, 10, 6, 2, 10] let isStudentNice: Set<Bool> = [false, true, true, false, false] let prices: Set<Double> = [24.32, 45.32, 40.00, 1.45, 1.45, 24.32] let names: Set<String> = ["Theodore", "Theodore", "Ruth", "Chichi", "Amaka", "Theodore"] // print the sets to the console print(lectureId) print(userId) print(evenNumbers) print(isStudentNice) print(prices) print(names)
RELATED TAGS
CONTRIBUTOR
View all Courses