Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

ios - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...