当我们可以使用数组在swift中返回多个值时,为什么要使用元组 [英] Why to use tuples when we can use array to return multiple values in swift

查看:95
本文介绍了当我们可以使用数组在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.

数组正常但我们可以返回不同类型的多个值。好的很酷,但这也可以通过AnyObject数组完成,如下所示:

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




我们可以命名元组中存在的对象。好的,但我可以使用AnyObject的字典。

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

我不是说为什么在我们得到这个时使用元组。但是应该有一些只有元组可以做的事情,或者只有元组才能做到这一点。而且,如果没有充分的理由,创造swift的人就不会迅速参与元组。所以应该有一些很好的理由让他们参与其中。

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.

提前致谢。

推荐答案

元组是可用于的元组结构许多方法,其中之一是使函数返回多个值更容易。

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:


  • 多个类型可以存储在元组中,而在数组中,只限于一种类型(除非你使用 [AnyObject] ]

  • 固定数量的值:你不能传递比预期更少或更多的参数,而在数组中你可以放任意数量的参数

  • 强类型:如果不同类型的参数在错误的位置传递,编译器将检测到,而使用不会发生的数组

  • 重构:如果参数的数量或类型,更改,编译器将产生相关的编译错误,而对于将被忽略的数组

  • 命名:可以将名称与每个参数相关联

  • 分配更容易,更灵活 - 例如,可以将返回值分配给元组:

  • 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()

并且可以忽略一些值

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")
    

    (在Swift 2中不推荐使用)该功能也可以是调用为:

    (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

    这篇关于当我们可以使用数组在swift中返回多个值时,为什么要使用元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆