zoukankan      html  css  js  c++  java
  • Swift学习-Tuple、Dictionary、Set

    1.Tuple(元组)

    元组可以包含多种类型元素;元组中元素使用“,”分割。

    var firstTuple = ("Chloe","www.huihuang.com")
    print(firstTuple.0)
    print(firstTuple.1)
    //使用type(of:)可以获取元组类型
    print(type(of:firstTuple))//类型:(String,String)
    

    定义元组和定义变量相似。

    元组基本形式:
    var 元组名称 :(元素类型,元素类型,...) =  (element,element,...) 
    也可以简化为:
    var 元组名称 = (element,element)
    

    元组类型是从定义本身推断出来的;元组类型就是元组所有元素的类型;
    元组元素访问:使用点语法,后跟值的索引;
    可以给元组元素设置名称来访问元素。

    //空元组
    var voidTuple = ()
    //定义元组
    var tuple : (Int ,Bool) = (2,false)
    

    为元组元素命名:可以为元组元素命名,引用的时候使用名字;命名方式类似函数参形式。

    var namedTuple = (blogger : "huihuang",tutorial:"Swift Tuples",year:2021)
    print(namedTuple.blogger)//打印结果:huihuang
    print(namedTuple.tutorial)//打印结果:Swift Tuples
    print(namedTuple.year)//打印结果:2021
    

    分解元组

    我们可以从元组中查找元素,赋值给掐常量或变量

    var firstTuple = ("Chloe","www.huihuang.com")
    var (name,webSite) = firstTuple
    let (b,t,y) = namedTuple
    print(webSite)//打印结果:www.huihuang.com
    print(b)//huihuang
    let (_,websiteName) = firstTuple//_:表明忽略第一个元素。_在哪个元素位置,表明忽略哪个元素。
    

    使用元组交换数据

    如果它们是相同的类型,我们可以使用一个元组交换两个变量中的值

    var i = 10
    var j = 20
    (i,j) = (j,i)
    print("i is (i) j is (j)")
    

    元组是值类型

    var origin = (x:0,y:0,z:0)
    var newOrigin : (Int,Int,Int) = origin
    
    newOrigin.0 = 1
    newOrigin.1 = 5
    newOrigin.2 = 10
    print(origin)//(x:0,y:0,z:0)
    print(newOrigin)//(1,5,10)
    

    元组包含元组

    var nestedTuple = (("Swift","Swift tuples tutorial"),("Android","Android Volley Tutorial"))
    //调用方法
    nestedTuple.0.1 //Swift tuples tutorial
    

    使用Swift元组,我们可以从一个函数返回多个值

    func sumOfTwo(first a : Int,second b : Int) ->(Int,Int,Int){
        return(a,b,a+b)
    }
    
    var returnedTuple = sumOfTwo(first: 2, second: 3)
    returnedTuple.2 // 5
    

    要在返回的元组中设置元素名称,我们需要在元组类型定义本身中显式地设置它们。

    var returnedTupleNamed:(first: Int,second: Int,sum: Int) = sumOfTwo(first: 2, second: 3)
    

    2.Dictionary

    基本语法

    let dicionary:Dictionary<KeyType,ValueType> = [:]
    

    定义

    //1.
    var countryCodes = [String:Int]()
    countryCodes["India"] = 91
    countryCodes["USA"] = 1
    //2.
    var secondDictionary = ["Swift" : "iOS", "Java" : "Android" , "Kotlin" : "Android"]
    secondDictionary["Java"] //"Android"
    secondDictionary["Kotlin"] //"Android"
    secondDictionary["Java"] //nil;字典中不存在的key,value返回nil;如果要删除一个key,可以把value置为nil
    

    由两个数组组成字典

    let keys = ["August","Feb","March"]
    let values = ["Leo","Pisces","Pisces"]
    let zodiacDictionary = Dictionary(uniqueKeysWithValues: zip(keys, values))//由两个序列构成的成对序列
    print(zodiacDictionary)//打印结果:["Feb": "Pisces", "March": "Pisces", "August": "Leo"]
    

    根据数组元素及元素个数,生成字典;同时避免存在相同的key问题

    let zodiacs = ["Leo","Pisces","Pisces","Aries"]
    //uniquingKeysWith:保持字典中有唯一的key
    let repeatedKeysDict = Dictionary(zip(zodiacs, repeatElement(1, count: zodiacs.count)), uniquingKeysWith: +)
    print(repeatedKeysDict)//打印结果:["Aries": 1, "Leo": 1, "Pisces": 2]
    

    filter、mapping

    //filter、mapping
    let filtered = repeatedKeysDict.filter{ $0.value == 1}
    print(filtered)//打印结果:["Leo": 1, "Aries": 1]
    
    let mapped = filtered.mapValues{"Occurence is ($0)"}
    print(mapped)//打印结果:["Leo": "Occurence is 1", "Aries": "Occurence is 1"]
    
    
    let repeatedDicMapped = repeatedKeysDict.mapValues{"($0)"}
    print(repeatedDicMapped)//打印结果:["Aries": "1", "Pisces": "2", "Leo": "1"]
    
    let repeatedUpper = repeatedKeysDict.map{$0.key.uppercased()}
    print(repeatedUpper)//打印结果:["LEO", "PISCES", "ARIES"]
    

    3.Set

    Set作用

    1.用来存储相同类型并且没有确定顺序的值。
    2.可以存储的类型必须是可以哈希的;所以Swift的基础类型(比如String、Int、Double、Bool)默认都是可哈希的
    3.自定义类型需要实现Hashable协议
    4.由于哈希协议,所以Set存储值需要基于哈希值
    

    Set与Array不同之处

    1.Set存储的值是唯一的;Array可以重复存储。
    2.Set是无序的;Array是有序的。
    3.Set存储值基于哈希值;Array不是
    4.Set查询时间是恒定的;Array不是,所以查询Set比Array快。
    

    Set与Dictionary

    1.都是无序的。
    2.字典可以不同key对应同一个value;Set只有唯一的值。
    

    声明Set的三种形式

    //形式1:声明空集合,集合中存储String类型的数据
    var emptySet = Set<String>()
    emptySet = []
    print(emptySet)//打印结果:[]
    //形式2:声明一个存储类型为Int的集合;
    var filledSet : Set<Int> = [3,1,2]
    print(filledSet)//打印结果:[2,3,1]
    //形式3:声明一个集合,集合类型根据根据集合存储的数据类型Swift自行判断
    var typeInferredSet : Set = ["Red","Yellow","Green"]
    print(typeInferredSet)//打印结果:["Green", "Red", "Yellow"]
    //Insert、Remove元素
    emptySet.insert("One")
    emptySet.insert("Two")
    emptySet.insert("One")
    print(emptySet)//打印结果:["Two", "One"]
    
    //remove:删除集合中的元素,并返回元素;如果集合中不存在元素,返回nil
    var x = filledSet.remove(2)//打印结果:2
    var y = filledSet.remove(0)//打印结果:nil
    
    //获取元素1,在集合中的下标
    let storeIndex = filledSet.firstIndex(of: 1)
    //根据下标删除元素;当集合中不存在1时,storeIndex返回为nil
    if let unwrapped = storeIndex{
        filledSet.remove(at: unwrapped)
    }
    
    //删除全部
    filledSet.removeAll()
    //判断集合中是否存在某个元素
    typeInferredSet.contains("Red")
    
    //insert:向集合中插入元素;集合不支持add
    filledSet.insert(4)
    
    //集合中元素的个数
    filledSet.count//打印结果:1
    //判断集合是否为空
    filledSet.isEmpty//返回结果:false
    

    用Array创建Set

    /形式1
    let intSet = Set([5,4,1,6])
    //形式2
    let myArray = ["Monday","Tuesday"]
    let anotherSet = Set(myArray)
    
    let sequenceSet = Set<Int>(1...5)
    print(sequenceSet)
    //使用sorted()方法使集合保持有序.默认是升序排列
    var newSet : Set<Int> = [5,4,1,2,3]
    print(newSet)
    for words in newSet.sorted(){
        print(words)
    }
    //自定义降序排列
    for word in newSet.sorted(by: { (x, y) -> Bool in
        return x > y
    }){
        print(word)
    }
    

    比较两个集合

    1.子集合与父集合

    var setA : Set<String> = ["A","B","C","D","E"]
    var setB : Set<String> = ["C","D","E"]
    var setC : Set<String> = ["A","B","C","D","E"]
    
    setB.isSubset(of: setA) //true
    setB.isStrictSubset(of: setA) //true
    setC.isSubset(of: setA) //true
    setC.isStrictSubset(of: setA) //false
    setA.isSuperset(of: setB) //true
    setA.isStrictSuperset(of: setB) //true
    

    2.交集与并集

    var setA : Set<String> = ["A","B","C","D","E"]
    var setB : Set<String> = ["C","D","E"]
    var setC : Set<String> = ["A","B","C","D","E"]
    var setD : Set<String> = ["A","F"]
    
    //判断两个集合是否有交集
    setD.isDisjoint(with: setB)//true
    setD.isDisjoint(with: setA)//false
    //将两个集合合并
    var unionSet = setD.union(setA)
    print(unionSet)//打印结果: ["F", "B", "C", "E", "A", "D"]
    //取两个集合交集
    var inter = setD.intersection(setA) // {"A"}
    
  • 相关阅读:
    MySQL事务学习-->隔离级别
    ssh升级
    通过普通用户向各个节点服务器分发文件到各个目录
    parted在2T以上硬盘上分区操作
    时间同步出现ntpdate[1788]: the NTP socket is in use, exiting
    kvm解决1000M网卡问题
    mysql主从同步问题解决汇总
    ....
    iOS App Icon图标 尺寸规范
    SpringMVC注解配置
  • 原文地址:https://www.cnblogs.com/PotatoToEgg/p/15009835.html
Copyright © 2011-2022 走看看