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

前端 未结 4 1836
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 13:51

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.

相关标签:
4条回答
  • 2020-12-02 14:04

    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?

    0 讨论(0)
  • 2020-12-02 14:08

    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

    0 讨论(0)
  • 2020-12-02 14:13

    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!

    0 讨论(0)
  • 2020-12-02 14:19

    A tuple is ideally used to return multiple named data from a function for temporary use. If the scope of the tuple is persistent across a program you might want to model that data structure as a class or struct.

    0 讨论(0)
提交回复
热议问题