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
// Swift program to illustrate array // Creating and initializing an Array with Integer Values var arr:[ Int ] = [ 1, 2, 3, 4, 5 ] // Display the array print (arr) |
Output:
[1, 2, 3, 4, 5]
Example 2: Creating and initializing an Array with String Values
Swift
// Swift program to illustrate array // Creating and initializing an Array of String Values var arr = [ "GeeksforGeeks" , "GFG" , "Swift Programs" ] // Display the array 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
// Swift program to illustrate set // Creating and initializing set of Integer Values var set1 : Set = [ 1, 2, 2, 2, 3, 4 ] // Creating and initializing set of Integer Values var set2 : Set = [ "GeeksforGeeks" , "GFG" , "Swift Programs" , "Swift Programs" , "GFG" ] // Display the result 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. |
Please Login to comment...