Why to use tuples when we can use an array or a set in Swift 5 Code Programming? | Arrays vs sets vs tuples

Array in Swift,Swift Tupple ,Swift Set,tuples,tuples in swift,tuples with swift,how to use tuples in swift,programming with swift,swift tutorial with ios, ios development,xcode,array with swift, set with swift,tupple with ios,tupple with swift


Tuple in Swift:

A tuple is a process of grouping multiple values together as a single compound value. 

The values in a tuple can be of any type and do not need to be of the same type. 

If you want to hold strings, or an integer, or properly boolean, or similar, you should use a tuple.

Let's look at an example to explain this in more detail. 

Multiple types of value in a single let tupleObj & access elements through calling the index.

let tupleObj = ("Swift","iOS",5.6)
print(tupleObj.0) //Swift
print(tupleObj.1) //iOS
print(tupleObj.2) //5.6

Multiple types of value in a single var bookInfo & access values through calling the key. 

var bookInfo = (name: "Swift", version: "5.3")
print(bookInfo.name) // Swift
print(bookInfo.version) // 5.3

Set in Swift:

A set is an unordered collection of unique elements.

Set does not contain any index or key to access an element.

Set is faster when iterating through the collection.

If you want there to be no duplicates and the order does not matter, you will use a set.

Let's look at an example. 

var set = Set(["Swift", "Objective C", "iOS"])
set.insert("SwiftUI")
set.remove("Objective C")
set.count   // 3
print(set) //["iOS", "SwiftUI", "Swift"]

Arrays in Swift:

An array is simply a container that can hold an ordered collection of similar elements.

Array elemnets are accessed using index.

Array is bit slower when iterarting through the collection.

If you want to use items order is important and can include duplicates so you should use an array.

Let's look at an  array example. 

let languageArr = ["Swift", "Objective C","Swift", "iOS", "SwiftUI"]
print(languageArr)
print(languageArr[4])  //SwiftUI
//["Swift", "Objective C", "iOS", "SwiftUI"]




Post a Comment

0 Comments