美文网首页
Swift-元组

Swift-元组

作者: Joker_King | 来源:发表于2016-11-18 14:24 被阅读16次

元组将多个值分组为单个复合值。 元组中的值可以是任何类型,并且不必具有彼此相同的类型。
在此示例中,(404,“NotFound”)是描述HTTP状态代码的元组。 HTTP状态代码是Web服务器在您请求网页时返回的特殊值。 如果您请求的网页不存在,则会返回404未找到的状态代码。

let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")

您可以从任何类型的排列创建元组,并且它们可以包含任意多种不同类型。 没有什么能阻止你有一个类型(Int,Int,Int)或(String,Bool)的元组,或者你需要的任何其他排列。
您可以将表的内容分解为单独的常量或变量,然后您可以像平常一样访问:

let (statusCode, statusMessage) = http404Error
print("The status code is \(statusCode)")
// Prints "The status code is 404"
print("The status message is \(statusMessage)")
// Prints "The status message is Not Found"

如果只需要一些元组值,在分解元组时,使用下划线(_)忽略元组的一部分:

let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// Prints "The status code is 404"

或者,使用从零开始的索引号访问元组中的各个元素值:

print("The status code is \(http404Error.0)")
// Prints "The status code is 404"
print("The status message is \(http404Error.1)")
// Prints "The status message is Not Found"

当定义元组时,您可以在元组中给每个元素命名:

let http200Status = (statusCode: 200, description: "OK")

如果给元组中的元素命名,则可以使用元素名称访问这些元素的值:

print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200"
print("The status message is \(http200Status.description)")
// Prints "The status message is OK"

元组作为函数的返回值特别有用。 尝试检索网页的函数可能返回(Int,String)元组类型,以描述页面检索的成功或失败。 通过返回具有两个不同值的元组,每个值具有不同的类型,该函数提供关于其结果的更有用的信息,而不是返回单个类型的单个值。

相关文章

  • swift-元组

    元组:将多个数据放在一个类型当中 可以有任意多个值 不同的值可以是不同的类型 下划线代表忽略某个值

  • Swift-元组

    元组将多个值分组为单个复合值。 元组中的值可以是任何类型,并且不必具有彼此相同的类型。在此示例中,(404,“No...

  • 关情纸尾---swift-元组

    1.什么是元组 2.定义元组 3.定义元组其它方式

  • swift-类属性

    了解属性之前,需要先了解前面的swift-类结构内容 - swift-类结构源码探寻[https://www.ji...

  • Swift4.0 --- 第一节:变量和常量

    // // ViewControllerOne.swift // Swift-(1) // // Created ...

  • Swift4.0 --- 可选项

    // // ViewControllerTwo.swift // Swift-(1) // // Created ...

  • Swift4.0 --- 可选项的判断

    // // ViewControllerFour.swift // Swift-(1) // // Created...

  • Swift4.0 --- 逻辑分支

    // // ViewControllerThree.swift // Swift-(1) // // Create...

  • Python入门:元组

    六、元组 6.1 定义元组 元组和列表相似,列表是[---],元组是(---) 6.2 访问元组 6.3 修改元组...

  • Python 元组

    元组的创建和删除 访问元组元素 修改元组元素 元组推导式 元组与列表的区别

网友评论

      本文标题:Swift-元组

      本文链接:https://www.haomeiwen.com/subject/bzajpttx.html