美文网首页
Swift:集合类型

Swift:集合类型

作者: 懒懒米虫 | 来源:发表于2018-12-06 11:37 被阅读7次

    集合类型

    Swift的集合类型包括:数组,集合和字典。

    数组

    一个数组有序地存储着相同的类型数据。同一个数据可以同时出现在数组的不同位置。

    数组简写语法

    Swift数组的类型声明为:Array<\color{gray}{Element}>,一般简写为[\color{gray}{Element}],\color{gray}{Element} 即为数组存储的数据类型。

    创建空数组

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

    \color{gray}{someInts}的类型由构造器[Int]决定。

    如果数组的内容已经提供了类型信息,例如一个函数参数或者一个已经声明了类型的变量或者常量,你就可以通过一个空的数组字面量:[],创建一个空的数组。

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

    数组的初始化和操作

    // 通过默认值创建数组
    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]
    
    // 数组字面量创建数组
    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList has been initialized with two initial items
    // 由于Swift的类型推导,你也可以这样写:
    var shoppingList = ["Eggs", "Milk"]
    
    // 获取数据当前容量
    print("The shopping list contains \(shoppingList.count) items.")
    // Prints "The shopping list contains 2 items."
    
    // 判断是否为空
    if shoppingList.isEmpty {
        print("The shopping list is empty.")
    } else {
        print("The shopping list is not empty.")
    }
    // Prints "The shopping list is not empty."
    
    // 添加新元素
    shoppingList.append("Flour")
    // shoppingList now contains 3 items, and someone is making pancakes
    shoppingList += ["Baking Powder"]
    // shoppingList now contains 4 items
    shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
    // shoppingList now contains 7 items
    
    // 通过下标访问数据
    var firstItem = shoppingList[0]
    // firstItem is equal to "Eggs"
    
    // 修改某个下标的数据
    shoppingList[0] = "Six eggs"
    // the first item in the list is now equal to "Six eggs" rather than "Eggs"
    shoppingList[4...6] = ["Bananas", "Apples"]
    // shoppingList now contains 6 items
    
    // 插入
    shoppingList.insert("Maple Syrup", at: 0)
    // shoppingList now contains 7 items
    // "Maple Syrup" is now the first item in the list
    
    // 删除
    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
    firstItem = shoppingList[0]
    // firstItem is now equal to "Six eggs"
    let apples = shoppingList.removeLast()
    // the last item in the array has just been removed
    // shoppingList now contains 5 items, and no apples
    // the apples constant is now equal to the removed "Apples" string
    

    数组遍历

    通过for-in遍历数组

    for item in shoppingList {
        print(item)
    }
    // Six eggs
    // Milk
    // Flour
    // Baking Powder
    // Bananas
    

    通过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
    

    集合

    集合用来无序存储明确的数据类型,并且相同的数据只能出现一次。

    集合类型语法

    Swift的集合类型写法为:Set<Element>。Element即为集合存储的数据类型,和数组不同的是,集合没有数据那样的等价简写方式。

    创建并初始化一个集合

    var letters = Set<Character>()
    print("letters is of type Set<Character> with \(letters.count) items.")
    // Prints "letters is of type Set<Character> with 0 items."
    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
    // 类型推导
    var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
    

    获取和修改集合里面的值

    // 集合大小
    print("I have \(favoriteGenres.count) favorite music genres.")
    // Prints "I have 3 favorite music genres."
    
    // 是否为空
    if favoriteGenres.isEmpty {
        print("As far as music goes, I'm not picky.")
    } else {
        print("I have particular music preferences.")
    }
    // Prints "I have particular music preferences."
    
    // 插入删除
    favoriteGenres.insert("Jazz")
    // favoriteGenres now contains 4 items
    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."
    
    //查询
    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 genre in favoriteGenres {
        print("\(genre)")
    }
    // Classical
    // Jazz
    // Hip hop
    

    Swift的集合是无序的,为了有序的遍历集合,可以试用sorted()方法,该方法通过<运算符有序地返回集合元素。

    for genre in favoriteGenres.sorted() {
        print("\(genre)")
    }
    // Classical
    // Hip hop
    // Jazz
    

    集合的运算

    你可以组合两个集合,或者求出两个集合的共同元素或者不同元素等。

    基本运算

    集合基本运算

    1.使用intersection(:)方法创建一个新的集合,该集合包含两个集合的共同元素。
    2.使用symmetricDifference(
    :)方法,创建一个新的集合,该集合包含了两个集合中除了共同元素外的所有元素。
    3.union(:)方法,获取两个集合的并集。
    4.subtracting(
    :),获取a集合中,除了和b集合共同元素外的所有元素。

    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]
    

    集合的包含关系

    下图描述了3个集合a,b和c。集合a是b的超集,因为集合a包含了集合b的所有元素。相反,集合b是集合a的子集。集合b和集合c互斥,因为它们没有共同的元素。


    集合包含关系

    1.使用“==”运算符判断两个集合是否相同。
    2.使用isSubset(of:)方法,判断一个集合是否是指定集合的子集。
    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
    

    字典

    字典即无序的键值队列,一个唯一的键,对应着一个唯一的值。

    字典类型简写语法

    Dictionary<Key, Value>声明一个字典类型。简写形式:[Key: Value]更为通用。

    空字典创建

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

    通过字典字面量创建字典

    字典字面量格式如下:

    [key 1: value 1, key 2: value 2, key 3: value 3]

    var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    // 类型推导
    var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
    

    字典的获取和修改

    // 获取字典大小
    print("The airports dictionary contains \(airports.count) items.")
    // Prints "The airports dictionary contains 2 items."
    
    // 是否为空
    if airports.isEmpty {
        print("The airports dictionary is empty.")
    } else {
        print("The airports dictionary is not empty.")
    }
    // Prints "The airports dictionary is not empty."
    
    // 新增键值
    airports["LHR"] = "London"
    // the airports dictionary now contains 3 items
    
    // 修改键值
    airports["LHR"] = "London Heathrow"
    // the value for "LHR" has been changed to "London Heathrow"
    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."
    
    // 获取值
    if let airportName = airports["DUB"] {
        print("The name of the airport is \(airportName).")
    } else {
        print("That airport is not in the airports dictionary.")
    }
    
    // 删除键值对
    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
    if let removedValue = airports.removeValue(forKey: "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 (airportCode, airportName) in airports {
        print("\(airportCode): \(airportName)")
    }
    // YYZ: Toronto Pearson
    // LHR: London Heathrow
    
    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
    
    let airportCodes = [String](airports.keys)
    // airportCodes is ["YYZ", "LHR"]
    
    let airportNames = [String](airports.values)
    // airportNames is ["Toronto Pearson", "London Heathrow"]
    

    相关文章

      网友评论

          本文标题:Swift:集合类型

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