美文网首页
Swift中的元组

Swift中的元组

作者: keisme | 来源:发表于2017-05-08 15:18 被阅读15次

    元组把多个值组合成一个复合值,元组内的值可以是任意类型。

    let http404Eror = (404, "Not Found")
    // http404Error的类型是(Int, String)
    

    元组的内容可以分解成单独的可使用的常量和变量:

    let (statusCode, statusMessage) = http404Error
    print("The status code is \(statusCode)")
    print("The status message is \(statusMessage)")
    

    如果只需要分解一部分元组值,可以用_标记要忽略的部分:

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

    此外,还可以通过下标来访问元组中的单个元素:

    print("The status code is \(http404Error.0)")
    print("The status code is \(http404Error.1)")
    

    定制元组的时候可以给单个元素命名:

    let http200Status = (statusCode: 200, description: "OK")
    print("The status code is \(http200Status.statusCode)")
    print("The status message is \(http200Status.description)")
    

    强烈推荐给元祖的元素命名,可以使代码更清晰。

    作为函数返回值时,元组非常有用:

     func getSize() -> (statusCode: Int, description: String) {
        return (200, "OK")
     }
     
     let x = getSize()
     print("code is \(x.statusCode), descripiton is \(x.description)")
     // or
     print("code is \(getSize().statusCode), descripiton is \(getSize().description)")
     // print "code is 200, descripiton is OK"
    

    注意:
    元组在临时组织值得时候很有用,但是并不适合创建复杂的数据结构。如果你的数据结构并不是临时使用,请使用类或者结构体。

    相关文章

      网友评论

          本文标题:Swift中的元组

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