Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why to use tuples when we can use array to return multiple values in swift

Today I was just going through some basic swift concepts and was working with some examples to understand those concepts. Right now I have completed studying tuples.

I have got one doubt i.e, what is the need of using tuples ? Ya I did some digging on this here is what I got :

We can be able to return multiple values from a function. Ok but we can also do this by returning an array.

Array ok but we can return an multiple values of different types. Ok cool but this can also be done by array of AnyObject like this :

    func calculateStatistics (scores:[Int])->[AnyObject] {     var min = scores[0]     var max = scores[0]     var sum = 0          for score in scores     {         if score > max{             max = score         }         else if score < min{             min = score         }         sum += score     }     return [min,max,"Hello"] }  let statistics = calculateStatistics([25,39,78,66,74,80])  var min = statistics[0] var max = statistics[1] var msg = statistics[2] // Contains hello 

We can name the objects present in the tuples. Ok but I can use a dictionary of AnyObject.

I am not saying that Why to use tuples when we have got this . But there should be something only tuple can be able to do or its easy to do it only with tuples. Moreover the people who created swift wouldn't have involved tuples in swift if there wasn't a good reason. So there should have been some good reason for them to involve it.

So guys please let me know if there's any specific cases where tuples are the best bet.

Thanks in advance.

like image 232
iamyogish Avatar asked Nov 06 '14 06:11

iamyogish


People also ask

Why do we use tuples in Swift?

Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call.

What is difference between tuple and array in Swift?

Both tuples and arrays allow us to hold several values in one variable, but tuples hold a fixed set of things that can't be changed, whereas variable arrays can have items added to them indefinitely.

Can tuple return multiple values?

Note : Tuple can also be used to return two values instead of using pair .

Which Swift type is used to group multiple values into a single compound value?

Tuples group multiple values into a single compound value.


1 Answers

Tuples are anonymous structs that can be used in many ways, and one of them is to make returning multiple values from a function much easier.

The advantages of using a tuple instead of an array are:

  • multiple types can be stored in a tuple, whereas in an array you are restricted to one type only (unless you use [AnyObject])
  • fixed number of values: you cannot pass less or more parameters than expected, whereas in an array you can put any number of arguments
  • strongly typed: if parameters of different types are passed in the wrong positions, the compiler will detect that, whereas using an array that won't happen
  • refactoring: if the number of parameters, or their type, change, the compiler will produce a relevant compilation error, whereas with arrays that will pass unnoticed
  • named: it's possible to associate a name with each parameter
  • assignment is easier and more flexible - for example, the return value can be assigned to a tuple:

    let tuple = functionReturningTuple() 

    or all parameters can be automatically extracted and assigned to variables

    let (param1, param2, param3) = functionReturningTuple() 

    and it's possible to ignore some values

    let (param1, _, _) = functionReturningTuple() 
  • similarity with function parameters: when a function is called, the parameters you pass are actually a tuple. Example:

    // SWIFT 2 func doSomething(number: Int, text: String) {     println("\(number): \(text)") }  doSomething(1, "one")  // SWIFT 3     func doSomething(number: Int, text: String) {     print("\(number): \(text)") }  doSomething(number: 1, text: "one") 

    (Deprecated in Swift 2) The function can also be invoked as:

    let params = (1, "one") doSomething(params) 

This list is probably not exhaustive, but I think there's enough to make you favor tuples to arrays for returning multiple values

like image 121
Antonio Avatar answered Sep 19 '22 22:09

Antonio