简体   繁体   English

如何在功能上有效地使用元组?

[英]How to use tuples effectively in function?

Swift programming book says, Swift编程书说,

By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. 通过返回具有两个不同值(每个类型均不同)的元组,该函数提供的结果信息比仅返回单个类型的单个值要有用得多。

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. 摘自:Apple Inc.“快速编程语言”。iBooks。 https://itun.es/gb/jEUH0.l https://itun.es/gb/jEUH0.l

I searched on internet but couldn't find any examples of it.So I tried myself like example below, but if you've got better please let me know.. Thanks in advance. 我在互联网上进行搜索,但找不到任何示例。因此,我尝试了以下示例,但是如果您感觉更好,请让我知道。

var statusCode = 404
var statusMessage = "No Site"

let http404 = ( sCode : statusCode , sMessage : statusMessage)

func responseFromWS (foo : Int, bar : String) -> (param1 : Int, param2 : String)
{
    statusCode = foo
    statusMessage = bar

    let httpProtocol = ( statusCode , statusMessage)

    return httpProtocol
}


responseFromWS(500, "Internal Server Error")

输出量

In other languages (including objective c) you can return one value only (of any type), but in some cases you might need to return more than one value. 在其他语言(包括目标c)中,您只能返回一个值(任何类型),但是在某些情况下,您可能需要返回多个值。

The pattern usually applied in those cases is to pass references to variables to the function for all additional return values - a typical case is a reference to a NSError * variable, which the function either sets to nil if no error occurs, or to an instance of NSError in case of error. 在这些情况下通常采用的模式是将对变量的引用传递给该函数以获取所有其他返回值-典型情况是对NSError *变量的引用,如果没有错误发生,该函数要么设置为nil,要么对一个实例进行引用错误时的NSError错误。

Such problem is elegantly solved in swift using multiple return values packed in a tuple. 使用封装在元组中的多个返回值可以快速解决此问题。

The way you are using this features seems correct, but what's wrong is defining the statusCode and statusMessage variables outside the function scope: 您使用此功能的方式似乎是正确的,但是错误的是在函数范围之外定义statusCodestatusMessage变量:

func responseFromWS (foo : Int, bar : String) -> (code: Int, message: String)
{
    let statusCode: Int = foo
    let statusMessage: String = bar

    return (code: statusCode, message: statusMessage)

    // Note: you can also write as follows, because the parameter names are defined in the function signature
    // return (statusCode, statusMessage)
}

You can use the return value in different ways. 您可以通过不同的方式使用返回值。 As a tuple: 作为元组:

let response = responseFromWS(500, "Internal Server Error")

// Using named parameters
println(response.code) // Prints 500
println(response.message) // Prints "Internal Server Error"

// using parameters by index
println(response.0) // Prints 500
println(response.1) // Prints "Internal Server Error"

As individual variables: 作为单个变量:

let (code, message) = responseFromWS(500, "Internal Server Error")

println(code)
println(message)

As a subset of individual variables (if you need only a subset of the returned values): 作为单个变量的子集(如果仅需要返回值的子集):

// Assign message only, discard code
let (_, message) = responseFromWS(500, "Internal Server Error")

println(message)

In addition to the uses mentioned by @Antonio, I have used them to return "pseudo-structs" where a function calculates several values, but the definition of a new struct type would really not be used anywhere else. 除了@Antonio提到的用法之外,我还使用它们来返回“伪结构”,其中函数计算多个值,但是在其他任何地方实际上都不会使用新的结构类型的定义。

An example: when calculating true bearing and distance on the surface of the earth, one may choose to return some kind of polar coordinate struct, but the reverse azimuth (not a trivial relation in true geodesy) is also calculated as a by product. 一个例子:在计算地球表面的真实方位和距离时,可以选择返回某种极坐标结构,但是反向方位角(在真实大地测量学中不是微不足道的关系)也作为副产品来计算。 In implementations in other languages I have done this by defining a struct type to return the three doubles - but this struct type is never used except to call this function! 在其他语言的实现中,我通过定义一个结构类型以返回三个双精度字符来完成此操作-但是,除非调用此函数,否则永远不要使用该结构类型! Better to say 最好说

let (distance, azimuth, reverseAzimuth) = coordinate(vectorTo: otherCoordinate)

than having your future self look up the definition of and then unpack some obscure struct. 而不是让您将来的自己查看的定义,然后解压缩一些晦涩的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM