加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

《swift2.0 官方教程中文版》 第2章-04集合类型

发布时间:2020-12-14 01:37:33 所属栏目:百科 来源:网络整理
导读:import Foundation //Swift 语言中的 Arrays 、 Sets 和 Dictionaries 中存储的数据值类型必须明确。这意味着我们不能把不正确的数 据类型插入其中。 /* 集合的可变性 ***********************************************/ /* 数组 **************************


import Foundation


//Swift 语言中的ArraysSetsDictionaries中存储的数据值类型必须明确。这意味着我们不能把不正确的数 据类型插入其中。


/*集合的可变性***********************************************/




/*数组***********************************************/

// 创建数组

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 被推断为 [Double],等价于 [2.5,2.5,2.5]

var sixDoubles = threeDoubles + anotherThreeDoubles

// sixDoubles 被推断为 [Double],2.5]


//我们可以使用字面量来进行数组构造,这是一种用一个或者多个数值构造数组的简单方法。

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

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

//也可以这样写 var shoppingList = ["Eggs","Milk"]


print("The shopping list contains (shoppingList.count) items.")

// 输出 "The shopping list contains 2 items."(这个数组有2个项)


//使用布尔值属性 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 不是空的)


//也可以使用 append(_:) 方法在数组后面添加新的数据项:

shoppingList.append("Flour")

// shoppingList 现在有3个数据项


//除此之外,使用加法赋值运算符( += )也可以直接在数组后面添加一个或多个拥有相同类型的数据项:

shoppingList += ["Baking Powder"]

// shoppingList 现在有四项了

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

// shoppingList 现在有七项了

print(shoppingList)


var firstItem = shoppingList[0] // 第一项是 "Eggs"

shoppingList[0] = "Six eggs"

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


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

// shoppingList 现在有6

print(shoppingList)


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

print(shoppingList)


let mapleSyrup = shoppingList.removeAtIndex(0)

print(mapleSyrup)

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

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

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


let apples = shoppingList.removeLast()

print(apples)

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

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

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


//我们可以使用 for-in 循环来遍历所有数组中的数据项:

for item in shoppingList {

print("item is (item)")

}


//如果我们同时需要每个数据项的值和索引值,可以使用 enumerate() 方法来进行数组遍历。 enumerate() 返回 一个由每一个数据项索引值和数据值组成的元组。我们可以把这个元组分解成临时常量或者变量来进行遍历:

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

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

}




/*集合***********************************************/

//你可以通过构造器语法创建一个特定类型的空集合:

var letters = Set<Character>()

print("letters is of type Set<Character> with (letters.count) items.")

// 打印 "letters is of type Set<Character> with 0 items."


letters.insert("a")

// letters 现在含有1 Character 类型的值

letters = []

// letters 现在是一个空的 Set,但是它依然是 Set<Character> 类型


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

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


//一个 Set 类型不能从数组字面量中被单独推断出来,因此 Set 类型必须显式声明。然而,由于 Swift 的类型推断 功能,如果你想使用一个数组字面量构造一个 Set 并且该数组字面量中的所有元素类型相同,那么你无须写出 S et 的具体类型。

//favoriteGenres的构造形式可以采用简化的方式代替

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


print("I have (favoriteGenres.count) favorite music genres.")

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

}

// 打印 "I have particular music preferences."


//你可以通过调用 Set insert(_:) 方法来添加一个新元素:

favoriteGenres.insert("Jazz")


//你可以通过调用 Set remove(_:) 方法去删除一个元素,如果该值是该 Set 的一个元素则删除该元素并且返回 被删除的元素值,否则如果该 Set 不包含该值,则返回 nil 。另外,Set 中的所有元素可以通过它的 removeAl l() 方法删除。

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


//使用 contains(_:) 方法去检查 Set 中是否包含一个特定的值:

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


//你可以在一个 for-in 循环中遍历一个 Set 中的所有值。

for genre in favoriteGenres {

print("(genre)")

}


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

for genre in favoriteGenres.sort() {

print("=====(genre)")

}


//基本集合操作

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

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

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

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


let oddDigits: Set = [1,3,5,7,9]

let evenDigits: Set = [0,2,4,6,8]

let singleDigitPrimeNumbers: Set = [2,7]


print(oddDigits.union(evenDigits).sort())

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

print(oddDigits.intersect(evenDigits).sort())

// []

print(oddDigits.subtract(singleDigitPrimeNumbers).sort())

// [1,9]

print(oddDigits.exclusiveOr(singleDigitPrimeNumbers).sort())

// [1,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




/*字典***********************************************/




/*字典类型快捷语法***********************************************/

//Swift 的字典使用 Dictionary<Key,Value> 定义,其中 Key 是字典中键的数据类型,Value 是字典中对应于这 些键所存储值的数据类型。


//我们可以像数组一样使用构造语法创建一个拥有确定类型的空字典:

var namesOfIntegers = [Int: String]()

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

namesOfIntegers[16] = "sixteen"

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

namesOfIntegers = [:]

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




/*用字典字面量创建字典***********************************************/

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


//字典也可以用这种简短方式定义:

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


print("The dictionary of airports contains (airports.count) items.")

// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)


if airports.isEmpty {

print("The airports dictionary is empty.")

} else {

print("The airports dictionary is not empty.")

}

// 打印 "The airports dictionary is not empty."


airports["LHR"] = "London"

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

airports["LHR"] = "London Heathrow"

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

print(airports)


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

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

}

// 输出 "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.")

}

// 打印 "The name of the airport is Dublin Airport."


airports["APL"] = "Apple Internation"

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

print(airports)

airports["APL"] = nil

// APL 现在被移除了

print(airports)


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

}


//通过访问 keys 或者 values 属性,我们也可以遍历字典的键或者值:

for airportCode in airports.keys {

print("Airport code: (airportCode)")

}

for airportName in airports.values {

print("Airport name: (airportName)")

}


//如果我们只是需要使用某个字典的键集合或者值集合来作为某个接受 Array 实例的 API 的参数,可以直接使用 keys 或者 values 属性构造一个新数组:

let airportCodes = [String](airports.keys.sort())

print(airportCodes)

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

let airportNames = [String](airports.values)

print(airportNames)

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



//Swift 的字典类型是无序集合类型。为了以特定的顺序遍历字典的键或值,可以对字典的 keys values 属性使 sort() 方法。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读