Swift3.0P1 语法指南——集合类型
Swift提供三种原始的集合类型:数组、集合、字典,这三种类型在使用时key和value的类型都是确定的,意味着只有类型对应的元素才能保存到相应的集合中。

1、集合类型的可变性
一旦将集合类型声明为常量,其大小和内容都不能再变化。
2、数组(Array)
数组用于存储有序的同一类型的数据元素。
(1)数组的简写
数组类型的全写为: Array<Element>,其中,Element是元素的类型。
可以简写为:[Element].
(2)创建空的数组
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// prints "someInts is of type [Int] with 0 items."
如果数组的类型已知,可用[]将其赋值为空数组。
someInts.append()
// someInts now contains 1 value of type Int
someInts = []
// someInts is now an empty array, but is still of type [Int]
(3)用默认的值来创建数组
var threeDoubles = Array(repeating: 0.0, count: )
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
以下是V2.1的对应方法:
1 var threeDoubles = [Double](count: 3, repeatedValue: 0.0)
2 // threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
(4)通过两个数组相加,创建一个数组
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]
(5)通过字面值创建一个数组
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items
由于有了类型推断,不必声明数组的类型,如下,Swift会将shoppingList推断为[String]类型:
var shoppingList = ["Eggs", "Milk"]
(6)访问和修改数组
count属性得到数组的长度:
print("The shopping list contains \(shoppingList.count) items.")
// prints "The shopping list contains 2 items."
isEmpty属性判断数组是否为空:
if shoppingList.isEmpty {
print("The shopping list is empty.")
} else {
print("The shopping list is not empty.")
}
// prints "The shopping list is not empty."
append(_:)方法,在后面插入字符串:
shoppingList.append("Flour")
// shoppingList now contains 3 items, and someone is making pancakes
也可以直接用+=运算符:
shoppingList += ["Baking Powder"]
// shoppingList now contains 4 items
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList now contains 7 items
通过下标,访问数组中的元素:
var firstItem = shoppingList[]
// firstItem is equal to "Eggs"
通过下标,改变数组中的元素:
shoppingList[] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"
可以使用范围运算符改变一定范围下边内的数组元素, 如下,将"Chocolate Spread", "Cheese", :"Butter"替换为"Bananas" 和"Apples":
shoppingList[...] = ["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
移除元素:
let mapleSyrup = shoppingList.remove(at: 0)
// the item that was at index 0 has just been removed
// shoppingList now contains 6 items, and no Maple Syrup
// the mapleSyrup constant is now equal to the removed "Maple Syrup" string
如果移除最后一个元素,请使用removeLast()方法:
let apples = shoppingList.removeLast()
// the last item in the array has just been removed
// shoppingList now contains 5 items, and no apples
// the apples constant is now equal to the removed "Apples" string
(7)遍历数组
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
如果既需要值,又需要下标,则使用 enumerate()方法:
for (index, value) in shoppingList.enumerate() {
print("Item \(index + 1): \(value)")
}
// Item 1: Six eggs
// Item 2: Milk
// Item 3: Flour
// Item 4: Baking Powder
// Item 5: Bananas
3、集合(Set)
集合用于存储值各不相同的同一类型的元素。
(1)元素的Hash值
要能够被存储在集合中,数据类型一定要hashable,也就是说该类型需提供一定方法来计算它的Hash值。Hash值是一种整型的数据,对于相等的所有对象而言,其Hash值是相同的。
如果a == b,则a.hashValue == b.hashValue。
Swift的基本类型 String, Int, Double, 和Bool,默认都是hashable,可以用作Set的value类型或者Dictionary的key类型。没有关联值的枚举中的值也是默认hashable。
注意:你可以把自定义的类型用作Set的value类型或者Dictionary的key类型,只要它们实现Hashable协议。要实现Hashable协议,则该类型需要有一个gettable的名为hashValue的Int属性。该属性在不同程序或者同一程序的不同执行情况下不一定要返回相同的值。由于Hashable协议遵守了Equatable协议,所以也必须实现相等比较运算符(==),== 的实现必须遵循以下要求:
a == a(Reflexivity)a == bimpliesb == a(Symmetry)a == b && b == cimpliesa == c(Transitivity)
(2)Set的声明
Set<Element>,其中,Element是元素的类型。
(3)创建并初始化一个空的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."
此外,如果Set已经明确类型,则可以用[]将Set赋为空:
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>
(4)用数组字面量来声明一个Set
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items
Set类型不能只由数组字面量来推断出,所以Set关键字必须显示地声明。由于数组的元素类型是可以推断出来的,Set的value类型可以不用显示声明。
var favoriteGenres: Set = ["Rock", "Classical", "Hip hop"]
(5)访问和修改Set
访问元素数量:
print("I have \(favoriteGenres.count) favorite music genres.")
// prints "I have 3 favorite music genres."
Set是否为空:
if favoriteGenres.isEmpty {
print("As far as music goes, I'm not picky.")
} else {
print("I have particular music preferences.")
}
// prints "I have particular music preferences."
添加元素:
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items
移除元素:
if let removedGenre = favoriteGenres.remove("Rock") {
print("\(removedGenre)? I'm over it.")
} else {
print("I never much cared for that.")
}
// prints "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.")
}
// prints "It's too funky in here."
(6)遍历Set
for genre in favoriteGenres {
print("\(genre)")
}
// Classical
// Jazz
// Hip hop
以某种指定顺序遍历Set(用<进行排序):
for genre in favoriteGenres.sorted() {// for genre in favoriteGenres.sort() V2.1
print("\(genre)")
}
// Classical
// Hip hop
// Jazz
(7)Set运算

并集、异或、交集、差集
let oddDigits: Set = [, , , , ]
let evenDigits: Set = [, , , , ]
let singleDigitPrimeNumbers: Set = [, , , ] oddDigits.union(evenDigits).sort()
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
oddDigits.intersection(evenDigits).sort()
// []
oddDigits.subtracting(singleDigitPrimeNumbers).sort()
// [1, 9]
oddDigits.symmetricDifference(singleDigitPrimeNumbers).sort()
// [1, 2, 9]
(8)Set之间的关系
== 判断两个Set的元素是否完全相同。isSubsetOf(_:)判断Set中的所有元素是否包含在另一Set中。isSupersetOf(_:)判断Set是否包含另一Set的所有元素。isStrictSubsetOf(_:)或者isStrictSupersetOf(_:)判断set是否是另一Set的超集或子集,并且并不相等。isDisjointWith(_:)判断两个Set是否有交集。
let houseAnimals: Set = ["Swift3.0P1 语法指南——集合类型的更多相关文章
- Swift3.0P1 语法指南——下标
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——构造器
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——方法
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——属性
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——类和结构体
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——枚举
原档: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programm ...
- Swift3.0P1 语法指南——闭包
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——函数
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
- Swift3.0P1 语法指南——基本操作符
原档:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programmi ...
随机推荐
- Solution: Win 10 和 Ubuntu 16.04 LTS双系统, Win 10 不能从grub启动
今年2月份在一台装了Windows的机器上装了Unbuntu 14.04 LTS (双系统, dual-boot, 现已升级到 16.04 LTS). 然而开机时要从grub启动 Windows (选 ...
- [Android]Message,MessageQueue,Looper,Handler详解+实例
转http://www.eoeandroid.com/forum-viewthread-tid-49595-highlight-looper.html 一.几个关键概念 1.MessageQueue: ...
- 超强语感训练文章(Provided by Rocky teacher Prince)
Content: Class1 My name is Prince Class2 Welcome to our hotel Class3 We’re not afraid of problems Cl ...
- DNS(二)之bind的视图功能
bind视图工作原理 在我国目前的网络环境下面,多个运营商并存,运营商之间的存在一定的网络互通问题,如果把来自不同的运营商或者地域的所有用户通过简单的A记录分配到一个机房,那么就存在部分网民访问延时大 ...
- 通过rsync搭建一个远程备份系统(一)
前言 我公司是电子商务公司,全部是linux系统,每天的网站数都在增加,为了保证安全,需要建立一个远程容灾系统,将网站数据每天凌晨1点备份到远程服务器上,由于数据量大,每天进行进行增量备份,仅仅备份当 ...
- RBAC权限设计实例
http://blog.csdn.net/painsonline/article/details/7183629 实现业务系统中的用户权限管理 B/S系统中的权限比C/S中的更显的重要,C/S系统因为 ...
- 生成N个二进制位的组合
#include "stdafx.h" #include "stdlib.h" #include "stdio.h" #include &l ...
- Java线程:Timer和TimerTask
Timer和TimerTask可以做为实现线程的第三种方式,前两中方式分别是继承自Thread类和实现Runnable接口. Timer是一种线程设施,用于安排以后在后台线程中执行的任务.可安排任务执 ...
- Linux服务器间文件传输
利用scp传输文件 1.从服务器下载文件 scp username@servername:/path/filename /tmp/local_destination 例如scp codinglog@1 ...
- Timer类和TimerTask类
Timer类是一种线程设施,可以用来实现在某一个时间或某一段时间后安排某一个任务执行一次或定期重复执行. 该功能要与TimerTask类配合使用.TimerTask类用来实现由Timer安排的一次或重 ...