美文网首页
Swift3.0之集合类型

Swift3.0之集合类型

作者: 青鸟evergreen | 来源:发表于2016-08-10 14:41 被阅读74次

    一、数组
    通过初始化语法创建一个特定类型的空数组

    var someInts = [Int]()
    print("someInts is of type [Int] with\(someInts.count) items")
    

    如果上文已提供类型信息,像函数参数或者已有类型的常变量,可以使用空数组字面量来创建空数组,写作[]

    someInts.append(3)
    // someInts now contains 1 value of type Int
    someInts = []
    // someInts is now an empty array, but is still of type [Int]
    

    创建一个带默认值的数组
    Swift提供初始化器来创建一种所有值为同一个默认值的特定大小的数组。通过repeating:来传递一个默认值,通过count:来传递这个值出现的次数。如下:

    var threeDoubles = Array(repeating:0.0,count:3)
    // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
    

    两数组合并组成新数组
    使用+

    var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
    // anotherThreeDoubles is of type [Double], and equals [2.5, 2.5, 2.5]
    var sixDoubles = threeDoubles + anotherThreeDoubles
    // sixDoubles is inferred as [Double], and equals [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]
    

    通过数组字面量来创建一个数组
    如下格式:
    [value 1, value2, value3]

    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList has been initialized with two initial items
    

    一般你不用写数组的类型,因为数组字面量中的所有值都为同种类型,Swift可以自动算出正确地类型。

    var shoppingList = ["Eggs", "Milk"]
    

    访问和修改数组
    可以通过其方法和属性来访问修改一个数组,或者使用下标语法
    (1) 数组item的数目,使用count属性

    print("The shopping list contains \(shoppingList.count) items.")
    // Prints "The shopping list contains 2 items."
    

    (2)使用isEmpty来判断数组是否为空
    (3)通过append(_:)的方式来添加新的item

    shoppingList.append("Flour")
    // shoppingList now contains 3 items, and someone is making pancakes
    

    (4)检索数组的值,通过下标的方式

    var firstItem = shoppingList[0]
    // firstItem is equal to "Eggs"
    

    注意:swift中数组下标总是以0开头的
    (5)可以通过下标语法来直接修改值

    shoppingList[0] = "Six eggs"
    // the first item in the list is now equal to "Six eggs" rather than "Eggs"
    

    (6)可以通过下标来改变一个范围的值

    shoppingList[4...6] = ["Bananas", "Apples"]
    // shoppingList now contains 6 items
    

    注意:不能使用下标来拼接一个新的item到数组的最后
    (7)在特定的索引下,插入一个数组,使用 insert(_:at:)方法

    shoppingList.insert("Maple Syrup", at: 0)
    // shoppingList now contains 7 items
    // "Maple Syrup" is now the first item in the list
    

    (8)使用remove(at:)来移除item,返回被移除的item

    let mapleSyrup = shoppingList.remove(at: 0)
    // the item that was at index 0 has just been removed
    // shoppingList now contains 6 items, and no Maple Syrup
    // the mapleSyrup constant is now equal to the removed "Maple Syrup" string
    

    注意:访问超出边界会报错
    (9)移除数组最后一个item,最好使用removeLast(),省去查找数组个数的属性,同样,removeLast返回被移除的item

    let apples = shoppingList.removeLast()
    

    (10)遍历一个数组

    for item in shoppingList {
    print(item)
    }
    

    (11)如果你需要每一个item的整形指数以及值,可以使用enumerated()来遍历数组。那么返回的值为指数和对应的值组成的元组。

    for (index, value) in shoppingList.enumerated() {
    print("Item \(index + 1): \(value)")
    }
    // Item 1: Six eggs
    // Item 2: Milk
    // Item 3: Flour
    // Item 4: Baking Powder
    // Item 5: Bananas
    

    二、集合

    存储一些同一类型没有顺序的值,并且每个item只出现一次。
    为了能让类型储存在集合当中,它必须是可哈希的——就是说类型必须提供计算它自身哈希值的方法。
    Swift 的合集类型写做 Set<Element>,这里的 Element是集合要储存的类型。不同与数组,集合没有等价的简写。

    初始化创建一个空的集合

     var letters = Set<Character>()
    

    如果上文已提供类型信息,通过空的数组字面量创建一个空的集合

    letters.insert("a")
    // letters now contains 1 value of type Character
    letters = []
    // letters is now an empty set, but is still of type Set<Character>
    

    使用数组字面量初始化一个数组,可以作为一个速成的方式写进更多的值

    var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
    // favoriteGenres has been initialized with three initial items
    

    一个set类型不能仅仅通过数组字面量来推出,所以set必须能明确的声明,但是如果数组字面量包含的类型与集合初始化的类型一致,集合内的类型不用写出

    var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
    

    访问和修改一个集合
    (1)count, isEmpty属性同上
    (2)添加item, insert(_:)

    favoriteGenres.insert("Jazz")
    

    (3)remove(_:)移除item,返回被移除的值,如果不包含这个item,则返回nil。所有item可以被removeAll()移除

    if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
    } else {
    print("I never much cared for that.")
    }
    // Prints "Rock? I'm over it."
    

    (4)检测是否包含一个item,使用contains(_:)

    if favoriteGenres.contains("Funk") {
    print("I get up on the good foot.")
    } else {
    print("It's too funky in here.")
    }
    // Prints "It's too funky in here."
    

    遍历合集
    for - in . Set 如果按特定的顺序,使用 sorted()方法。

    for genre in favoriteGenres.sorted() {
    print("\(genre)")
    }
    

    集合操作

    集合
    (1)使用 intersection(:)找出两个集合共有的部分并成为新的集合
    (2)使用symmetricDifference(
    :)找出连个集合各自用的值,不是共有的
    (3)union(:)合并两个集合
    (4)subtracting(
    :)元素不在指定的集合
    let oddDigits: Set = [1, 3, 5, 7, 9]
    let evenDigits: Set = [0, 2, 4, 6, 8]
    let singleDigitPrimeNumbers: Set = [2, 3, 5, 7]
    oddDigits.union(evenDigits).sorted()
    // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    oddDigits.intersection(evenDigits).sorted()
    // []
    oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
    // [1, 9]
    oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted()
    // [1, 2, 9]
    

    从属和等价关系
    (1)使用= 来判断两个集合是否完全包含相同元素
    (2)isSubset(0f:)来判断子集合
    (3)isSuperset(of:)判断父集合
    (4)isStrictSubset(of:) 或者 isStrictSuperset(of:)来判断是否一个集合完全是子集或父集合,而不是等同于一个特定的集合
    (5)isDisjoint(with:)来判断是否有相同元素

    let houseAnimals: Set = ["🐶", "🐱"]
    let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
    let cityAnimals: Set = ["🐦", "🐭"]
    houseAnimals.isSubset(of: farmAnimals)
    // true
    farmAnimals.isSuperset(of: houseAnimals)
    // true
    farmAnimals.isDisjoint(with: cityAnimals)
    // true
    

    三、字典
    创建空字典,如果已知道类型,可写成[:]

    var namesOfIntegers = [Int: String]()
    namesOfIntegers[16] = "sixteen"
    // namesOfIntegers now contains 1 key-value pair
    namesOfIntegers = [:]
    // namesOfIntegers is once again an empty dictionary of type [Int: String]
    

    以字典字面量的形式创建一个字典

    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    

    和数组一样,如果和初始化的键值类型一致,那么就不用再写相关类型。

    var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    

    访问和修改字典
    (1)count和isEmpty属性。
    (2)下标脚本给字典添加新元素。使用正确类型的新键作为下标脚本的索引,然后赋值一个正确类型的值

    airports["LHR"] = "London"
    // the airports dictionary now contains 3 items
    

    同样可以通过key修改Value

    airports["LHR"] = "London Heathrow"
    // the value for "LHR" has been changed to "London Heathrow"
    

    (3)使用updateValue(:forkey:)来设置或更新一个特定key所对应的值。做完更新后,这个方法返回旧的Value。
    updateValue(
    :forKey:)方法返回一个字典值类型的可选项值。比如对于储存 String值的字典来说,方法会返回 String?类型的值,或者说“可选的 String”。这个可选项包含了键的旧值如果更新前存在的话,否则就是 nil:

    if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("The old value for DUB was \(oldValue).")
    }
    // Prints "The old value for DUB was Dublin."
    

    同样可以使用下标脚本语法来从字典的特点键中取回值。由于可能请求的键没有值,字典的下标脚本返回可选的字典值类型。如果字典包含了请求的键的值,下标脚本就返回一个包含这个键的值的可选项。否则,下标脚本返回 nil :

    使用下标脚本语法给一个键赋值 nil来从字典当中移除一个键值对:

    airports["APL"] = "Apple International"
    // "Apple International" is not the real airport for APL, so delete it
    airports["APL"] = nil
    // APL has now been removed from the dictionary
    

    使用 removeValueForKey(_:)来从字典里移除键值对。这个方法移除键值对如果他们存在的话,并且返回移除的值,如果值不存在则返回 nil:

    if let removedValue = airports.removeValueForKey("DUB") {
        print("The removed airport's name is \(removedValue).")
    } else {
        print("The airports dictionary does not contain a value for DUB.")
    }
    // prints "The removed airport's name is Dublin Airport."
    

    遍历字典
    使用 for-in循环来遍历字典的键值对。字典中的每一个元素返回为 (key, value)元组,你可以解开元组成员到临时的常量或者变量作为遍历的一部分:

    for (airportCode, airportName) in airports {
        print("\(airportCode): \(airportName)")
    }
    // YYZ: Toronto Pearson
    // LHR: London Heathrow
    

    同样可以通过访问字典的 keys和 values属性来取回可遍历的字典的键或值的集合:

    for airportCode in airports.keys {
        print("Airport code: \(airportCode)")
    }
    // Airport code: YYZ
    // Airport code: LHR
    
    for airportName in airports.values {
        print("Airport name: \(airportName)")
    }
    // Airport name: Toronto Pearson
    // Airport name: London Heathrow
    

    需要和接收 Array实例的 API 一起使用字典的键或值,就用 keys或 values属性来初始化一个新数组:

    let airportCodes = [String](airports.keys)
    // airportCodes is ["YYZ", "LHR"]
    let airportNames = [String](airports.values)
    // airportNames is ["Toronto Pearson", "London Heathrow"]
    

    相关文章

      网友评论

          本文标题:Swift3.0之集合类型

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