归类 : Swift

Swift集合类型数据结构的demo示例

1. 区间运算符

闭区间运算符

闭区间运算符( a...b )定义了从 a 到 b 的一组范围,并且包含 a 和 b 。 a 的值不能大于 b 。

    for index in 1...5 {
        print("\(index) times 5 is \(index * 5)")
    }

半开区间运算符

半开区间运算符( a..

    let names = ["Anna", "Alex", "Brian", "Jack"]
    let count = names.count
    for i in 0..<count {
        print("Person \(i + 1) is called \(names[i])")
    }

单侧区间

让区间朝一个方向尽可能的远——比如说,一个包含数组所有元素的区间,从索引 2 到数组的结束。

    let names = ["Anna", "Alex", "Brian", "Jack"]
    for name in names[2...] {
        print(name)
    }
    // Brian
    // Jack
    for name in names[...2] {
        print(name)
    }
    // Anna
    // Alex
    // Brian

2. 集合(Collections)

1. 元组

元组把多个值合并成单一的复合型的值。元组内的值可为任何类型。

    let http404Error = (404, "Not Found")

1. 分解元组


    let (statusCode, statusMessage) = http404Error
    print("The status code is \(statusCode)")
    // prints "The status code is 404"
    print("The status message is \(statusMessage)")
    // prints "The status message is Not Found"

2. 不需要的数据可以用下滑线( _ )代替


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

3. 从零开始的索引数字访问元组中的单独元素

    print("The status code is \(http404Error.0)")
    // prints "The status code is 404"
    print("The status message is \(http404Error.1)")
    // prints "The status message is Not Found"

4. 单个元素命名

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

2. 数组(Array)

数组以有序的方式来储存相同类型的值

Swift 的 Array类型提供了初始化器来创建确定大小且元素都设定为相同默认值的数组。你可以传给初始化器对应类型的默认值(叫做 repeating)和新数组元素的数量(叫做 count):

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

使用数组字面量来初始化一个数组

    var shoppingList: [String] = ["Eggs", "Milk"]
    // shoppingList has been initialized with two initial items
    var shoppingList2 = ["Eggs", "Milk"]
    // 类型推断,省略[String]声明

1. 访问和修改数组

    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
    if shoppingList.count > 3{
        shoppingList.swapAt(1,2)
    }
    //互换位置 swapAt

2. 遍历数组

for-in循环来遍历数组

    for item in shoppingList {
        print(item)
    }

使用 enumerated()方法来遍历数组,(index, element)->(下标,元素)

    for (index, value) in shoppingList.enumerated() {
        print("Item \(index + 1): \(value)")
    }

3. 合集(Set)

  • 集合存储的数据类型是单一的
  • 集合是无序的
  • 集合中的任意值是唯一的

合集将同一类型且不重复的值无序地储存在一个集合当中

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

1. 访问和修改合集

    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."

2. 遍历合集

for-in循环遍历合集

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

Swift 的 Set类型是无序的。要以特定的顺序遍历合集的值,使用 sorted()方法,它把合集的元素作为使用 < 运算符排序了的数组返回。

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

3. 合集操作

    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]

4. 字典(Dictionary)

  • 字典基于键值对(key-value)这种映射关系来表示数据组织形式的
  • 键值具有唯一性
  • 键、值的类型必须是单一的,没有混搭的风格
  • 字典是无序的
  • 键必须满足哈希特性

字典储存无序的互相关联的同一类型的键和同一类型的值的集合

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

1. 访问和修改字典

    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.")
    }
    // prints "The name of the airport is Dublin Airport."
    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."

2. 遍历字典

for-in循环来遍历字典的键值对

    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

使用keys或 values属性来初始化一个新数组

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

以上