4.集合

2016-04-13  本文已影响0人  liushong

Array

var someInts = [Int]()

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

// 打印 "someInts is of type [Int] with 0 items。"

someInts.append(3)

// someInts 现在包含一个Int值

someInts = []

// someInts 现在是空数组,但是仍然是[Int]类型的。

var threeDoubles = [Double](count: 3, repeatedValue:0.0)

// threeDoubles 是一种 [Double]数组, 等于 [0.0, 0.0, 0.0]

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)

// anotherThreeDoubles is inferred as [Double], and equals [2.5, 2.5, 2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles

// sixDoubles 被推断为 [Double], 等于 [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]

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

// shoppingList 已经被构造并且拥有两个初始项。

使用布尔项isEmpty来作为检查count属性的值是否为 0 的捷径。

if shoppingList.isEmpty {

print("The shopping list is empty.")

} else {

print("The shopping list is not empty.")

}

// 打印 "The shopping list is not empty."(shoppinglist不是空的)

shoppingList += ["Baking Powder"]

// shoppingList 现在有四项了

shoppingList += ["Chocolate Spread","Cheese","Butter"]

// shoppingList 现在有七项了

var firstItem = shoppingList[0]

// 第一项是 "Eggs"

shoppingList[0] = "Six eggs"

// 其中的第一项现在是 "Six eggs" 而不是 "Eggs"

还可以利用下标来一次改变一系列数据值,即使新数据和原有数据的数量是不一样的。下面的例子把"Chocolate Spread","Cheese",和"Butter"替换为"Bananas"和 "Apples":

shoppingList[4...6] = ["Bananas", "Apples"]

// shoppingList 现在有六项

注意: 不可以用下标访问的形式去在数组尾部添加新项。

shoppingList.insert("Maple Syrup", atIndex: 0)

// shoppingList 现在有7项

// "Maple Syrup" 现在是这个列表中的第一项

let mapleSyrup = shoppingList.removeAtIndex(0)

// 索引值为0的数据项被移除

// shoppingList 现在只有6项,而且不包括Maple Syrup

// mapleSyrup常量的值等于被移除数据项的值 "Maple Syrup"

let apples = shoppingList.removeLast()

// 数组的最后一项被移除了

// shoppingList现在只有5项,不包括cheese

// apples 常量的值现在等于"Apples" 字符串

for (index, value) in shoppingList.enumerate() {

print("Item \(String(index + 1)): \(value)")

}

// Item 1: Six eggs

// Item 2: Milk

// Item 3: Flour

// Item 4: Baking Powder

// Item 5: Bananas

Set

var letters = Set()

print("letters is of type Setwith \(letters.count) items.")// 打印 "letters is of type Setwith 0 items."

letters.insert("a")// letters 现在含有1个Character类型的值letters = []// letters 现在是一个空的Set, 但是它依然是 Set类型

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

// favoriteGenres被构造成含有三个初始值的集合

favoriteGenres.insert("Jazz")

// favoriteGenres 现在包含4个元素

if let removedGenre = favoriteGenres.remove("Rock") {

print("\(removedGenre)? I'm over it.")

} else {

print("I never much cared for that.")

}

// 打印 "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.")

}

// 打印 "It's too funky in here."

Swift 的Set类型没有确定的顺序,为了按照特定顺序来遍历一个Set中值可以使用sort()方法,它将根据提供的序列返回一个排序的集合.

for genre in favoriteGenres.sort() {

print("\(genre)")

}

// prints "Classical"

// prints "Hip hop"

// prints "Jazz

使用intersect(_:)方法根据两个集合中都包含的值创建的一个新的集合。

使用exclusiveOr(_:)方法根据值在一个集合中但不在两个集合中的值创建一个新的集合。

使用union(_:)方法根据两个集合的值创建一个新的集合。

使用subtract(_:)方法根据不在该集合中的值创建一个新的集合。

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).sort()

// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

oddDigits.intersect(evenDigits).sort()

// []

oddDigits.subtract(singleDigitPrimeNumbers).sort()

// [1, 9]

oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort()

// [1, 2, 9]

使用“是否等”运算符(==)来判断两个集合是否包含全部相同的值。

使用isSubsetOf(_:)方法来判断一个集合中的值是否也被包含在另外一个集合中。

使用isSupersetOf(_:)方法来判断一个集合中包含的值是另一个集合中所有的值。

使用isStrictSubsetOf(_:)或者isStrictSupersetOf(_:)方法来判断一个集合是否是另外一个集合的子集合或者父集合并且和特定集合不相等。

使用isDisjointWith(_:)方法来判断两个结合是否不含有相同的值。

let houseAnimals: Set = ["🐶", "🐱"]

let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]

let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubsetOf(farmAnimals)

// true

farmAnimals.isSupersetOf(houseAnimals)

// true

farmAnimals.isDisjointWith(cityAnimals)

// true

Dictionary

var namesOfIntegers = [Int: String]()

// namesOfIntegers 是一个空的 [Int: String] 字典

namesOfIntegers[16] = "sixteen"

// namesOfIntegers 现在包含一个键值对

namesOfIntegers = [:]

// namesOfIntegers 又成为了一个 Int, String类型的空字典

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

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

airports["LHR"] = "London"

// airports 字典现在有三个数据项

airports["LHR"] = "London Heathrow"

// "LHR"对应的值 被改为 "London Heathrow

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {

print("The old value for DUB was \(oldValue).")

}

// 输出 "The old value for DUB was Dublin."

airports["APL"] = "Apple Internation"

// "Apple Internation"不是真的 APL机场, 删除它

airports["APL"] = nil

// APL现在被移除了

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 (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 = Array(airports.keys)

// airportCodes is ["YYZ", "LHR"]

let airportNames = Array(airports.values)

// airportNames is ["Toronto Pearson", "London Heathrow"]

上一篇下一篇

猜你喜欢

热点阅读