zoukankan      html  css  js  c++  java
  • Swift 元组

    
    /*
     元组相当于关系数据库中的一条记录,它将多个任意数据类型的值合并为一个值。
     元组类型的值的语法格式为:(元素1, 元素2, ..., 元素n)。
     */
    let turple = ("张三", 18, true)
    // let turple: (String, Int, Bool) = ("张三", 18, true)
    
    
    /*
     如果想要访问元组中的元素,有以下几种方式:
     (1)使用索引值访问(索引值从0开始)
     */
    turple.0
    turple.1
    turple.2
    
    /*
     (2)为元组中的元素指定名字,然后使用指定的名字访问。
     */
    let turple2 = (name: "张三", age: 18, isMarried: true)
    
    turple2.name
    turple2.age
    turple2.isMarried
    
    
    let turple3: (name: String, age: Int, isMarried: Bool) = ("张三", 18, true)
    
    turple3.name
    turple3.age
    turple3.isMarried
    
    /*
     (3)把元组中的元素分解成多个变量或常量,然后使用变量名或常量名访问。
        此外,可以使用这种方式同时声明并初始化多个变量或常量。
     */
    let (name, age, isMarried) = ("张三", 18, true)
    
    name
    age
    isMarried
    
    // 定义元组变量,并指定初始值,系统推断该元组类型为(Int, Int, String)
    var health = (182 , 78 , "良好")
    // 使用元组类型来定义元组变量
    var score : (Int , Int , String , Double)
    // 为元组变量赋值时必须为所有成员都指定值
    score = (98 , 89 , "及格" , 20.4)
    
    // 元组的成员又是元组
    var test : (Int , (Int , String))
    test = (20 , (15 , "Swift"))
    
    // 输出元组
    print("health元组的值为:(health)")
    print("score元组的值为:(score)")
    print("test元组的值为:(test)")
    
    
    // 根据索引访问元组的元素
    print("health元组的身高元素为:(health.0)")
    print("health元组的体重元素为:(health.1)")
    print("score元组的Swift为:(score.0)")
    print("score元组的Objective-C为:(score.2)")
    print("test元组的第2个元素的第1个元素为:(test.1.0)")
    
    
    // 将元组拆分成多个变量
    var (height ,weight, status) = health
    print("身高:(height)、体重:(weight)、身体状态:(status)")
    
    // 将元组拆分成多个常量, 忽略元组的第4个元素
    let (swift, oc , lua, _) = score
    print("Swift成绩:(swift)、OC成绩:(oc)、Lua成绩:(lua)")
    
    
    // 定义元组变量,并指定初始值
            // 系统推断该元组类型为(height:Int, 体重:Int, status:String)
            let health = (height:182 , 体重:78 , status:"良好")
            // 使用元组类型来定义元组变量
            var score : (swift:Int , oc:Int , lua:String , ruby:Double)
            // 简单地为每个元素指定值,此时必须按顺序为每个元素指定值
            score = (98 , 89 , "及格" , 20.4)  // ①
            // 通过key为元组的元素指定值,在这种方式下,元组内各元素的顺序可以调换
            score = (oc:89 , swift:98 , lua:"及格" , ruby:4.4)  // ②
            
            
            print("health的身高为:(health.height)")
            print("health的体重为:(health.体重)")
            print("Swift成绩:(score.swift),OC成绩:(score.oc),"
                + "Lua成绩:(score.lua),Ruby成绩:(score.ruby)")
    
    
    
  • 相关阅读:
    全景转换工具
    Leetcode 215.数组中的第k个最大元素
    Leetcode 214.最短回文串
    Leetcode 213.大家劫舍II
    Leetcode 212.单词搜索II
    Leetcode 211.添加与搜索单词
    Leetcode 209.长度最小的子数组
    Leetcode 208.实现前缀树
    Leetcode 207.课程表
    Leetcode 206.反转链表
  • 原文地址:https://www.cnblogs.com/jukaiit/p/10173775.html
Copyright © 2011-2022 走看看