数组
- 创建一个空数组
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// 打印 "someInts is of type [Int] with 0 items."
//注意,通过构造函数的类型, someInts 的值类型被推断为 [Int] 。
someInts.append(3)
// someInts 现在包含一个 Int 值
someInts = []
// someInts 现在是空数组,但是仍然是 [Int] 类型的。
- 创建一个带默认值的数组
Swift 中的 Array 类型还提供一个可以创建特定大小并且所有数据都被默认的构造方法。我们可以把准备加入新 数组的数据项数量( count )和适当类型的初始值( repeating )传入数组构造函数:
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]
- 通过两个数组相加创建一个数组
var anotherThreeDoubles = Array(repeating: 2.5, count: 3)
// anotherThreeDoubles 被推断为 [Double],等价于 [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 已经被构造并且拥有两个初始项。
shoppingList 变量被声明为“字符串值类型的数组“,记作 [String] 。 因为这个数组被规定只有 String 一种 数据结构,所以只有 String 类型可以在其中被存取。 在这里, shoppingList 数组由两个 String 值( "Eggs" 和 "Milk" )构造,并且由数组字面量定义。
- 访问和修改数组
可以使用数组的只读属性 count 来获取数组中的数据项数量:
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 现在有七项了
可以直接使用下标语法来获取数组中的数据项,把我们需要的数据项的索引值放在直接放在数组名称的方括号
中:
var firstItem = shoppingList[0]
// 第一项是 "Eggs"
我们也可以用下标来改变某个已有索引值对应的数据值:
shoppingList[0] = "Six eggs"
// 其中的第一项现在是 "Six eggs" 而不是 "Eggs"
调用数组的 insert(_:at:) 方法来在某个具体索引值之前添加数据项:
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 现在有7项
// "Maple Syrup" 现在是这个列表中的第一项
我们可以使用 remove(at:) 方法来移除数组中的某一项
let mapleSyrup = remove(at: 0)
// 索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除数据项的值 "Maple Syrup"
- 数组遍历
我们可以使用 for-in 循环来遍历所有数组中的数据项:
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
如果我们同时需要每个数据项的值和索引值,可以使用 enumerated() 方法来进行数组遍历。 enumerated() 返回 一个由每一个数据项索引值和数据值组成的元组。我们可以把这个元组分解成临时常量或者变量来进行遍历:
for (index, value) in shoppingList. enumerated() {
print("Item \(String(index + 1)): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
集合
-
合类型的哈希值
一个类型为了存储在 合中,该类型必须是可哈希化的--也就是说,该类型必须提供一个方法来计算它的哈希 值。一个哈希值是 Int 类型的,相等的对象哈希值必须相同,比如 a==b ,因此必须 a.hashValue == b.hashValu e。
Swift 的所有基本类型(比如 String , Int , Double 和 Bool )默认都是可哈希化的,可以作为 合的值的类型或 者字典的键的类型。没有关联值的枚举成员值(在枚举有讲述)默认也是可哈希化的。 -
创建和构造一个空的集合
你可以通过构造器语法创建一个特定类型的空 合:
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items.")
// 打印 "letters is of type Set<Character> with 0 items."
通过一个空的数 组字面量创建一个空的 Set :
letters.insert("a")
// letters 现在含有1个 Character 类型的值
letters = []
// letters 现在是一个空的 Set, 但是它依然是 Set<Character> 类型
- 用数组字面量构建集合
创建一个称之为 favoriteGenres 的 合来存储 String 类型的值:
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被构造成含有三个初始值的 合
- 访问和修改一个集合
一个 Set 中元素的数量,可以使用其只读属性 count :
print("I have \(favoriteGenres.count) favorite music genres.")
// 打印 "I have 3 favorite music genres."
使用布尔属性 isEmpty 作为一个缩写形式去检查 count 属性是否为 0 :
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")
// favoriteGenres 现在包含4个元素
调用 Set 的 remove(_:) 方法去删除一个元素,另外, 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)")
}
// Classical
// Jazz
// Hip hop
按照特定顺序来遍历一个 Set 中的值可以使用 sorted() 方法,它将返回一个有序数组
for genre in favoriteGenres.sorted() {
print("(genre)")
}
// prints "Classical"
// prints "Hip hop"
// prints "Jazz
集合操作
- 基本集合操作
- 使用 intersection(_:) 方法根据两个 合中都包含的值创建的一个新的 合。
- 使用 symmetricDifference(_:) 方法根据在一个 合中但不在两个 合中的值创建一个新的 合。
- 使用 union(_:) 方法根据两个 合的值创建一个新的 合。
- 使用 subtracting(_:) 方法根据不在该 合中的值创建一个新的
- 集合成员关系和相等
- 使用“是否相等”运算符( == )来判断两个 合是否包含全部相同的值。
- 使用 isSubset(of:) 方法来判断一个 合中的值是否也被包含在另外一个 合中。
- 使用 isSuperset(of:) 方法来判断一个 合中包含另一个 合中所有的值。
- 使用 isStrictSubset(of:) 或者 isStrictSuperset(of:) 方法来判断一个 合是否是另外一个 合的子 合或 者父 合并且两个 合并不相等。
- 使用 isDisjoint(with:) 方法来判断两个 合是否不含有相同的值(是否没有交 )。
字典
- 创建一个空字典
var namesOfIntegers = Int: String
// namesOfIntegers 是一个空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 [Int: String] 类型的空字典
- 用字典字面量创建字典
一个键值对是一个 key 和一个 value 的结合体。在字典字面量中,每一个键值对的键和值都由冒号分割。这些键 值对构成一个列表,其中这些键值对由方括号包含、由逗号分割:
[key 1: value 1, key 2: value 2, key 3: value 3]
- 访问和修改字典
通过字典的只读属性 count 来获取某个字典的数据项数量:
print("The dictionary of airports contains (airports.count) items.")
// 打印 "The dictionary of airports contains 2 items."(这个字典有两个数据项)
使用布尔属性 isEmpty 作为一个缩写形式去检查 count 属性是否为 0 :
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
作为另一种下标方法,字典的 updateValue(_:forKey:) 方法可以设置或者更新特定键对应的值。updateValue(_:forKey:) 方法会返回对应值的类型的可选值。
可以使用下标语法来通过给某个键的对应值赋值为 nil 来从字典里移除一个键值对:
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场, 删除它
airports["APL"] = nil
// APL 现在被移除了
此外, removeValue(forKey:) 方法也可以用来在字典中移除键值对。
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-in 循环来遍历某个字典中的键值对。
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
网友评论