Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

swift
communitycreator

How to create a set collection in Swift

Theodore Kelechukwu Onyejiaku

Overview

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 Set cannot.

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.

Syntax

setName: Set = [elements]

// specify by type
setName: Set<datatype> = [elements]
Syntax for creating a set collection in swift

Parameters

  • 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.

Return value

A Set object is returned.

Example

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)
Create a set collection in swift

Explanation

  • Lines 4 and 5: We create two sets in a literal way in Swift, without specifying the data type or types.
  • Lines 8–11: We create sets by specifying the data types.
  • Lines 14–19: We print to the console all the sets we have created.

RELATED TAGS

swift
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring