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

查看:25
本文介绍了当我们可以使用数组快速返回多个值时,为什么要使用元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我只是了解了一些基本的 swift 概念,并正在使用一些示例来理解这些概念.现在我已经完成了元组的学习.

我有一个疑问,即使用元组有什么需要?是的,我对此进行了一些挖掘,这就是我得到的:

<块引用>

我们可以从一个函数返回多个值.好的,但是我们也可以通过返回一个数组来做到这一点.

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

 func calculateStatistics (scores:[Int])->[AnyObject]{var min = 分数[0]var max = 分数[0]变量总和 = 0得分得分{如果分数 >最大限度{最大值 = 分数}else if score <分钟{min = 分数}总和 += 分数}返回 [min,max,你好"]}让统计 = 计算统计([25,39,78,66,74,80])var min = 统计[0]var max = 统计[1]var msg = statistics[2]//包含你好

<块引用>

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

我并不是说当我们得到这个时为什么要使用元组.但是应该有一些只有元组才能做到的事情,或者只有元组才能做到这一点.此外,如果没有充分的理由,创建 swift 的人不会在 swift 中涉及元组.所以他们应该有充分的理由参与其中.

所以如果有任何特定情况下元组是最好的选择,请告诉我.

提前致谢.

解决方案

元组是匿名结构,可以有多种使用方式,其中之一就是让函数返回多个值更容易.

使用元组而不是数组的优点是:

  • 可以在一个元组中存储多种类型,而在数组中,您只能存储一种类型(除非您使用 [AnyObject])
  • 固定数量的值:您不能传递比预期更少或更多的参数,而在数组中您可以放置​​任意数量的参数
  • 强类型:如果不同类型的参数传递到错误的位置,编译器会检测到这一点,而使用不会发生的数组
  • 重构:如果参数的数量或它们的类型发生变化,编译器将产生相关的编译错误,而数组则会被忽略
  • 命名:可以为每个参数关联一个名称
  • 赋值更简单、更灵活——例如可以将返回值赋值给一个元组:

    let tuple = functionReturningTuple()

    或者所有参数可以自动提取并分配给变量

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

    并且可以忽略某些值

    let (param1, _, _) = functionReturningTuple()

  • 与函数参数的相似之处:调用函数时,传递的参数实际上是一个元组.示例:

    //SWIFT 2func doSomething(number: Int, text: String) {println("(数字): (文本)")}doSomething(1, "一")//斯威夫特 3func doSomething(number: Int, text: String) {打印((数字):(文本)")}doSomething(数字:1,文本:一")

    (在 Swift 2 中已弃用)该函数也可以调用为:

    让 params = (1, "one")做某事(参数)

这个列表可能并不详尽,但我认为这足以让您偏爱元组而不是数组以返回多个值

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.

解决方案

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

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

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