Swift – Difference Between Sets and Arrays
An array is a linear data structure which has contiguous memory in a single variable that can store N number of elements.
For example, if we want to take 10 inputs from the user we can’t initialise 10 variables. In this case you can make use of arrays. It can store N number of elements into a single variable. Elements can be accessed by using indexing.
Syntax:
var arr:[Int] = [value 1 , value 2 , value 3, . . . . value n]
Example 1: Creating and initializing an Array with Integer Values
Swift
var arr:[ Int ] = [ 1, 2, 3, 4, 5 ]
print (arr)
|
Output:
[1, 2, 3, 4, 5]
Example 2: Creating and initializing an Array with String Values
Swift
var arr = [ "GeeksforGeeks" , "GFG" , "Swift Programs" ]
print (arr)
|
Output:
[ "GeeksforGeeks", "GFG", "Swift Programs" ]
Set is a data structure where no duplicate elements are present. Generally, in arrays, we can store duplicate elements, but we can’t store duplicate elements in sets. By default, it eliminates duplicate elements. Like in mathematics we can perform set operations like union, intersection, set difference …etc.
Syntax:
var set_variable : Set=[value 1, value 2 , . . . . value n]
Example:
Swift
var set1 : Set = [ 1, 2, 2, 2, 3, 4 ]
var set2 : Set = [ "GeeksforGeeks" , "GFG" , "Swift Programs" , "Swift Programs" , "GFG" ]
print (set1)
print (set2)
|
Output :
[3, 4, 1, 2]
["GFG", "Swift Programs", "GeeksforGeeks"]
Note: Here we have taken duplicate elements while creating a set, but in the output, we can see there is no duplicate. Since the set doesn’t allow duplicates. Here the order of elements may change every time we print the set.
Difference between an Array and Set in Swift
Array
|
Set
|
Array is faster than set in terms of initialization. |
Set is slower than an array in terms of initialization because it uses a hash process. |
Parentheses ( ) are used to create arrays in swift |
Square braces [ ] are used to create set in swift |
The array allows storing duplicate elements in it. |
Set doesn’t allow you to store duplicate elements in it. |
Elements in the array are arranged in order. Or we can say that arrays are ordered. |
Elements in the set are not arranged in any specified order Or we can say that sets are unordered. |
Performance is not the main concern. |
Performance plays an important role. |
Last Updated :
04 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...