【问题标题】:Tuples in SwiftSwift 中的元组
【发布时间】:2014-09-22 22:59:30
【问题描述】:

Swift 中添加了一种新类型,即元组。 我只知道元组中的值可以是任何类型,并且不必彼此具有相同的类型。 但除此之外,还有什么是数组/字典不能做的,而元组可以,反之亦然?

【问题讨论】:

  • 不要将元组与数组和字典混淆。数组和字典是集合,但元组是将值分组为复合值。

标签: swift tuples


【解决方案1】:

啊,就在昨天,我使用返回元组的函数给出了答案。输出两个不同类型的值。有人想使用 switch 语句来匹配狗的名字和年龄:

func dogMatch(age: Int, name: String) -> (Match: String, Value: Int)  {

    switch (age, name) {
    case(age, "wooff"):
        println("My dog Fido is \(age) years old")
        return ("Match", 1)
    case (3, "Fido"):
        return ("Match", 10)
    default:
        return ("No Match", 0)
    }
}

dogMatch(3, "Fido").Match
dogMatch(3, "Fido").Value

注意元组包含不同类型的值。

【讨论】:

  • 那里没有数组 - 确保不要混淆元组和数组!
【解决方案2】:

想到的一件事是元组中的命名变量。在某些情况下,这比键或索引更可取:

let newTuple = (variableOne: 20, variableTwo: "Hi There")
newTuple.variableOne
newTuple.variableTwo

您可以使用typealias 进一步应用:

typealias namedTuple = (variableOne: Int, variableTwo: String)

let newTuple: namedTuple = (20, "Hi There")
newTuple.variableOne
newTuple.variableTwo

您还可以更明确地了解函数中的返回类型:

func controlledReturnType() -> (Int, String) {
    return (1, "Yup")
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 2014-12-19
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多