In this tutorial you will learn about the Swift Sets and its application with practical example.
Swift Sets
In Swift, Set is a unordered list of distinct values of same types. Set is much similar to an array but it is unordered and won’t allows duplicate elements, each value contained in a set is unique. Swift sets are typed, thus once you declare the type of the set or swift infers it then you would only have elements of the same type. Sets are useful when we want to hold distinct values of single data type in single variable and order of items is not important.
- Swift Sets
- Declaring Set In Swift
- Declaring/Initialize an empty Set
- Declaring/Initialize Set with a Sequence
- )
- Swift Get Set Elements Count
- Swift Add Elements using insert method
- Swift Finding Elements in a Set
- Swift Finding the Index of an Element in a Set
- Swift Remove Elements using remove method
- Swift Iterating Over a Set Elements
- Swift Set Equality
- Swift Set Operations
- Swift Set membership
Set values must be hashable which means it should comply with Hashable protocol and provide a hashValue property.It is important because set values are stored in unordered manner thus hashValue is used to access the set elements.
Declaring Set In Swift
There are multiple ways we can declare/initialize sets in swift.
Syntax:-
1 |
var set_var_name: Set<type> = [value, value, ...] |
Here, set_var_name is replaced with the set name and <type> is replaced with the data type of set and value, value, … will be replaced with actual values
Example:-
1 2 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print(persons) |
here, we initialized a set named persons of type String with values “John”, “Doe”, “Smith”, “Alex”.
Output:-
Note:- If we don’t specify the type explicitly then Swift automatically infers the type.
Declaring/Initialize an empty Set
In Swift, empty set can be created in following ways –
Syntax 1:-
1 |
var SetName = Set<Type>() |
Here, SetName is replaced with the name of set variable and Type is replaced with the data type of set.
Syntax 2:-
1 |
var secondSet = Set<Type>([]) |
Here, we have created a empty set named secondSet by passing an empty array literal [] and Type is replaced with the data type of set.
Declaring/Initialize Set with a Sequence
In Swift, it is possible to pass a sequence as a parameter which populate the elements within the set.
Example:-
1 2 3 |
var setOfInts = Set<Int>(1...5) print("W3Adda - Swift Creating Set using sequence") print(setOfInts) |
Output:-
Swift Check Set Empty (isEmpty)
In Swift, isEmpty property can be used to check whether the given set is empty or not.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] var marks: Set<Int> = [] print("W3Adda - Check empty set using isEmpty property.") if persons.isEmpty{ print("Persons set is empty.") } else{ print("Persons set is not empty.") } if marks.isEmpty{ print("Marks set is empty.") } else{ print("Marks set is not empty.") } |
Output:-
Swift Get Set Elements Count
In swift count property can be used to find the number of elements in a set.
Example:-
1 2 3 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Get Set element count.") print(persons.count) |
Output:-
Swift Add Elements using insert method
In Swift insert function is used to add or insert an element into given set.
Example:-
1 2 3 4 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] persons.insert("Murphy") print("W3Adda - Swift insert an Item into set.") print(persons) |
Output:-
Swift Finding Elements in a Set
In swift contains property can be used to find an element in a set, it takes a single element of the same type to be find within the set and returns a boolean value to indicate given element is exists or not.
Example:-
1 2 3 4 5 6 7 8 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Swift find an Item in set.") if persons.contains("Doe"){ print("Given element found.") } else{ print("Given element not found.") } |
Output:-
Swift Finding the Index of an Element in a Set
In Swift index(of:<ele>) method can be used to find the index of given elements, it takes a single element of the same type to be find within the set and returns index position if element is found in set.
Example:-
1 2 3 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] var pos = persons.index(of: "Doe") print(pos) |
Swift Remove Elements using remove method
In Swift remove function is used to remove or delete an element from given set.
Example:-
1 2 3 4 5 6 7 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Swift remove an element from set.") print("Before Delete") print(persons) print("After Delete") persons.remove("Doe") print(persons) |
Output:-
Swift Iterating Over a Set Elements
In Swift, we can loop through the set elements using for-in loop as following –
Example:-
1 2 3 4 5 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Iterating Set Elements.") for person in persons { print(person) } |
Output:-
In Swift, Set elements doesn’t have any defined order, we can use sorted() method to iterate over Set elements in a specified order.
Example:-
1 2 3 4 5 |
var persons: Set<String> = ["John", "Doe", "Smith", "Alex"] print("W3Adda - Iterating Set Elements using Sorted().") for person in persons.sorted() { print(person) } |
Output:-
Swift Set Equality
In Swift, equality of two sets can be tested using == operator. It returns true if two sets contains same elements otherwise returns false.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
var a: Set = [0, 2, 4, 6, 8] var b: Set = [0, 1, 5, 6, 8] var c: Set = [4, 2, 8, 0, 6] print("W3Adda - Check Set Equality") if a == b { print("a and b are same") } else { print("a and b are different") } if a == c { print("a and c are same") } else { print("a and c are different") } |
Output:-
Swift Set Operations
In swift we can perform some of the following basic set operations on any Set –
Union :- The union of two sets a and b is the set combining values of a and b.
intersection :- The intersection of two sets a and b is a set that contains all elements common in both sets.
subtracting :- The subtraction of two sets a and b is set containing all elements of set a and removing elements that belongs to set b.
Example:-
1 2 3 4 5 6 7 8 9 10 |
var a: Set = [10,12,14,16,18] var b: Set = [5,7,9,11,13] var c: Set = [2,3,5,7] print("W3Adda - Swift Set Operations") print("b union a is") print(b.union(a).sorted()) print("b intersection a is") print(b.intersection(a).sorted()) print("b subtracting c is") print(b.subtracting(c).sorted()) |
Output:-
Swift Set membership
isSubset(of:) :- This method is used to check if all of the values in a set are contained in specified set.
isSuperset(of:) :- This method is used to check if a set contains all the values exists in a specified set
isStrictSubset(of:) :- This method is used to check if a set is a subset of a specified set, but not equal to it.
isStrictSuperset(of:) :- This method is used to check if a set is a superset of a specified set, but not equal to it.
isDisjoint(with:) :- This method is used to check if two sets have no values in common.
Example:-
1 2 3 4 5 6 7 8 |
var a: Set = [1, 3, 5, 7, 9] var b: Set = [0, 3, 1, 7, 6, 8, 9, 5] print("W3Adda - Swift Set membership") print("a isSubset of b:", a.isSubset(of: b)) print("b isSuperset of a:", b.isSuperset(of: a)) print("a isStrictSubset of b:", a.isStrictSubset(of: b)) print("b isStrictSuperset of a:", b.isStrictSuperset(of: a)) print("a isDisjointWith of b:", a.isDisjoint(with: b)) |
Output:-