分类 标签 存档 黑客派 订阅 搜索

Swift 集合类型

128 浏览0 评论

Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。数组(Arrays)是有序数据的集。集合(Sets)是无序无重复数据的集。字典(Dictionaries)是无序的键值对的集。

集合的可变性

//如果创建一个Arrays、Sets或Dictionaries并且把它分配成一个变量,这个集合将会是可变的。这意味着我们可以在创建之后添加更多或移除已存在的数据项,或者改变集合中的数据项。如果我们把Arrays、Sets或Dictionaries分配成常量,那么它就是不可变的,它的大小和内容都不能被改变。

//注意:在我们不需要改变集合的时候创建不可变集合是很好的实践。如此 Swift 编译器可以优化我们创建的集合。

数组

//数组的简单语法
//写 Swift 数组应该遵循像Array<Element>这样的形式,其中Element是这个数组中唯一允许存在的数据类型。我们也可以使用像[Element]这样的简单语法。功能一样,推荐第二种简单语法.
//创建一个空数组
var someInt = Array<Int>()
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) 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 antherThreeDoubles = [Double](count: 3, repeatedValue: 2.5)
var sixDoubles = threeDoubles + antherThreeDoubles

//用字面量构造数组
var shoppingList: [String] = ["hello", "world"]
var tempShoppingList = ["hello", "world"] //因为swift的类型推断机制,所以我们不必把数组的类型定义清楚.

//访问和修改数组
print("The shopping list contains \(shoppingList.count) items")
//输出 The shopping list contains 2 items.
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("Flour")
//shoppingList 现在有3个数据项,有人在说 "你装的聪明点不行么"

shoppingList += ["Baking Powder"] //现在shoppingList有4项了
shoppingList += ["Chocolate Spread", "Cheese", "Butter"] //现在shoppingList有7项了

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

shoppingList[4...6] = ["Bananas", "Apples"]
//注意:不能用下标访问的形式给数组尾部添加新项

shoppingList.insert("Maple Syrup", atIndex: 0)
let mapleSyrup = shoppingList.removeAtIndex(0) //mapleSoyrup的值就是 Maple Syrup

firstItem = shoppingList[0] //现在第一项是 hi

let lastItem = shoppingList.removeLast() //移除数组最后一项,只剩5项,lastItem是 Apples

//数组的遍历
for item in shoppingList {
    print("***\(item)")
}

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

集合

//集合类型的哈希值
//集合类型语法
//Swift 中的Set类型被写为Set<Element>,这里的Element表示Set中允许存储的类型,和数组不同的是,集合没有等价的简化形式。
//创建和构造一个空集合
var letters = Set<Character>()
print("letters is of type Set<Character> with \(letters.count) items")

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

//数组字面量创建集合
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
var favoriteGenres1: Set = ["Rock", "Classical", "Hip hop"]

//访问和修改一个集合
print("I have \(favoriteGenres.count) favorite music genres.")

if favoriteGenres.isEmpty {
    print("As far as music goes, I'm not picky.")
} else {
    print("I have particular music preferences.")
}

favoriteGenres.insert("Jazz") //vavoriteGenres 现在包含4个元素
if let removedGenre = favoriteGenres.remove("Rock") {
    print("\(removedGenre)? I'm over it")
} else {
    print("I never much cared for that")
}

if favoriteGenres.contains("Funk") {
    print("I get up on the good foot")
} else {
    print("It's too funky in here") //因为不包含,所以打印这个
}

//遍历一个集合
for item in favoriteGenres {
    print("***\(item)")
}

for item in favoriteGenres.sort() {
    print("### \(item)")
}
//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 本集合是否包含另一个集合中的所有元素 
// isDisjointWith 用来判断是否没有交集,没有为true,有为false

let houseAnimals: Set = ["狗", "猫"]
let farmAnimals: Set = ["牛", "鸡", "羊", "狗", "猫"]
let cityAnimals: Set = ["鸟", "鼠"]
houseAnimals.isSubsetOf(farmAnimals) //true
farmAnimals.isSupersetOf(houseAnimals) //true
houseAnimals.isDisjointWith(cityAnimals) //true

字典

//字典类型的快捷语法
// Dictionary <Key, Value>
// var dic:[Key: Value] 
//通常使用后者

//创建一个空字典
var namesOfIntegers = [Int: String]() // namesOfIntegers 是一个空的 [Int: String]字典
namesOfIntegers[16] = "sixteen" //namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:] //nameOfInteger现在又变成了一个 [Int: String]类型的字典

//用字典字面量创建字典
var airports: [String: String] = ["YYZ": "Toronto pearson", "DUB": "Dublin"]

//访问和修改字典
print("The dictionary of airports contains \(airports.count) items")
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}

airports["LHR"] = "London"

airports["LHR"] = "London Heathrow"

if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
    print("&&The old value for DUB was \(oldValue)")
}

if let airportName = airports["DUB"] {
    print("))The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}

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 dicrionary does not contain a value for DUB")
}

//字典遍历
for (airportCode, airportName) in airports {
    print("@@\(airportCode): \(airportName)")
}

for airportCode in airports.keys.sort() {
    print("$$Airport code: \(airportCode)")
}
for airportName in airports.values.sort() {
    print("%%Airport Name: \(airportName)")
}

原文地址,非常感谢翻译者的持续更新.

--EOF--

评论  
留下你的脚步
推荐阅读