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

11,453

Solution 1

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

Solution 2

For example, consider this simple example:

enum MyType {
    case A, B, C
}

func foo() -> (MyType, Int, String) {
    // ...
    return (.B, 42, "bar")
}

let (type, amount, desc) = foo()

Using Array, to get the same result, you have to do this:

func foo() -> [Any] {
    // ...
    return [MyType.B, 42, "bar"]
}

let result = foo()
let type = result[0] as MyType, amount = result[1] as Int, desc = result[2] as String

Tuple is much simpler and safer, isn't it?

Solution 3

Tuple is a datastructure which is lighter weight than heterogeneous Array. Though they're very similar, in accessing the elements by index, the advantage is tuples can be constructed very easily in Swift. And the intention to introduce/interpolate this(Tuple) data structure is Multiple return types. Returning multiple data from the 'callee' with minimal effort, that's the advantage of having Tuples. Hope this helps!

Share:
11,453
iamyogish
Author by

iamyogish

Updated on June 15, 2022

Comments

  • iamyogish
    iamyogish almost 2 years

    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.