iOS开发程序员今日看点

Swift3.0集合类型(Collection Types)

2016-07-18  本文已影响1145人  Mustard_Buli

Swift一样有着三种基本集合类型,数组,集合,字典。


在Swift中,这三种类型总是很明确要存储的类型,这意味着不能再插入时犯错。

集合的可变性(Mutability of Collections)

当你用"var"来创建一个数组、集合、字典的时候,它就是可变的。

数组(Arrays)

Swift的Array桥接了Foundation的NSArray类

创建一个空数组(Creating an Empty Array)
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// Prints "someInts is of type [Int] with 0 items."

someInts.append(3)
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]
创建有默认值的数组(Creating an Array with a Default Value)
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
通过两个数组连接来创建一个数组(Creating an Array by Adding Two Arrays Together)

和字符串一样,可以通过"+"直接连接,🌰:

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]
使用字面值来创建数组(Creating an Array with an Array Literal)

这个方式最简单,也最常用:

//完整写法:var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList = ["Eggs", "Milk"]
//shoppingList has been initialized with two initial items

这种情况下创建的数组,只能存储String类型,如果是别的类型会抛出错误。

接收/修改数组(Accessing and Modifying an Array)
shoppingList.append("Bread")
//shoppingList now contains 3 items

也可以用"+="来追加元素

shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
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

当数组为空时(count = 0),数组的最大有效索引值总是count -1,因为索引值是从0开始的。

数组的遍历(Iterating Over an Array)

可以使用"for-in"循环。当需要索引值的时候,可以使用"enumerated()"方法,🌰:


🌰

index和value可以任意命名。

集合(Sets)

只能添加遵守Hashable协议的类型。

创建和初始化一个空的集合(Creating and Initializing an Empty Set)
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>
用数组字面量创建一个集合(Creating a Set with an Array Literal)
// 完整写法:var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
接收/修改集合(Accessing and Modifying a Set)
if let removeGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it.")
} else {
    print("I never much cared for that.")
}

// Prints "Rock? I'm over it."

集合的遍历(Iterating Over a Set)
for genre in favoriteGenres.sorted() {
    print("\(genre)")
}
// Classical
// Hip hop
// Jazz

Performing Set Operations(不知道怎么翻译了😂)

基本的集合操作(Fundamental Set Operations)
基本的集合操作
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]
集合的成员和相等(Set Membership and Equality)
let houseAnimals: Set = ["🐶", "🐱"]
let farmAnimals: Set = ["🐮", "🐔", "🐑", "🐶", "🐱"]
let cityAnimals: Set = ["🐦", "🐭"]

houseAnimals.isSubset(of: farmAnimals)
// true
farmAnimals.isSuperset(of: houseAnimals)
// true
farmAnimals.isDisjoint(with: cityAnimals)
// true

字典(Dictionaries)

key必须遵守Hashable协议。

创建空字典(Creating an Empty Dictionary)
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]
通过字面量来创建字典(Creating a Dictionary with a Dictionary Literal)
//完整写法
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
接收/修改字典(Accessing and Modifying a Dictionary)
airports["LHR"] = "London"
// the airports dictionary now contains 3 items

airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

也可以通过updateValue(_:forKey:)来完成追加、修改功能。当有该key时,返回旧值(old value);当没有该key时,返回nil,并且创建新的键值对。

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

或者使用"removeValue(forKey:)"方法来删除键值对,如果有则返回删除的值,如果没有则返回nil。

字典的遍历(Iterating Over a Dictionary)

使用"for-in"循环来遍历,返回的是(key, value)的元组,🌰:

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
let airportCodes = [String](airports.keys)
// airportCodes is ["YYZ", "LHR"]

let airportNames = [String](airports.values)
// airportNames is ["Toronto Pearson", "London Heathrow"]
上一篇 下一篇

猜你喜欢

热点阅读