Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Swift – Difference Between Sets and Arrays

  • Last Updated : 06 Dec, 2021

An array is a linear data structure which is having contiguous memory. In a single variable, we can store n number of elements. For example, if we want to take 10 inputs from the user we can’t initialize 10 variables. For that, we can use 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:

Swift




// Swift program to illustrate array
  
// Creating and initializing array
var arr:[Int] = [ 1, 2, 3, 4, 5 ]
  
// Display the array 
print(arr)

Output:

[1, 2, 3, 4, 5]

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




// Swift program to illustrate set
  
// Creating and initializing set
var set1:Set = [ 1, 2, 2, 2, 3, 4 ]
  
// Display the result
print(set1)

Output :

[2, 4, 1, 3]

Note: Here we have taken duplicate elements while creating 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 Array and Set

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 swiftSquare braces [ ] are used to create set in swift
The array allows to store duplicate elements in it.Set doesn’t allow 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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!