swift4.03 学习笔记(5)

集合类型

集合的可变性

如果你创建一个数组,集合,或字典变量,那么你可以添加,删除,修改集合中的元素。

如果你创建了数组,集合,或字典常量,那么你就不能添加,删除,修改集合中的元素。

数组

元素类型相同的有序的集合

创建空数组
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]
创建一个带默认值的数组
var threeDoubles = Array(repeating: 0.0, count: 3)
// threeDoubles is of type [Double], and equals [0.0, 0.0, 0.0]
  • repeating 要重复的值
  • count 重复的次数,数组的长度
两个数组连接成一个数组
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]

直接创建一个数组
var shoppingList: [String] = ["Eggs", "Milk"]
// shoppingList has been initialized with two initial items

自动推断类型

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

调用和修改数组

  • 只读属性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[0]
// firstItem is equal to "Eggs"
  • 通过索引修改索引指向的元素
shoppingList[0] = "Six eggs"
// the first item in the list is now equal to "Six eggs" rather than "Eggs"
  • 修改一个范围索引指向的元素
shoppingList[4...6] = ["Bananas", "Apples"]
// shoppingList now contains 6 items
  • insert(_:at:)在指定索引处插入一个元素,原该索引对应的元素及后面的后面的元素依次向后移
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList now contains 7 items
// "Maple Syrup" is now the first item in the list
  • remove(at:)移除指定索引位置的元素,该索引后面的元素依次向前移
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
遍历数组
for item in shoppingList {
    print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas

Set集合

没有相同值的无序集合

哈希值

set集合的元素必须可以得到哈希值。

创建并初始化一个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

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>

使用数组创建一个Set
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres has been initialized with three initial items 
访问和修改Set
  • 只读属性count获取Set集合的元素数量
print("I have \(favoriteGenres.count) favorite music genres.")
// Prints "I have 3 favorite music genres.
  • isEmpty属性,Set集合count是否0
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.
  • insert(_:)方法,往Set集合里插入一个元素
favoriteGenres.insert("Jazz")
// favoriteGenres now contains 4 items”

  • remove(_:)方法,移除Set集合中指定的元素,如果存在返回改元素,不存在返回nil
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."
  • removeAll()方法,移除Set集合中所有的元素
  • contains(_:)方法,判断Set集合中是否存在指定的元素
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."
  • sorted()方法,默认从小到大的顺序以数组的形式返回Set集合
let students: Set = ["Kofi", "Abena", "Peter", "Kweku", "Akosua"]
let sortedStudents = students.sorted()
print(sortedStudents)
// Prints "["Abena", "Akosua", "Kofi", "Kweku", "Peter"]"
遍历Set集合
for genre in favoriteGenres {
    print("\(genre)")
}
// Jazz
// Hip hop
// Classical
连接两个Set集合的方法
  • a.intersection(b) 创建一个新的Set集合,只包括两个Set集合中相同的元素
  • a.symmetricDifference(b) 创建一个新的集合,不包括两个集合中相同的元素
  • a.union(b)创建一个新集合,包括所有的元素
  • a.subtracting(b)创建一个新的集合,不包括b的任何元素
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]
判断一个集合是不是另一个集合的子
  • a.isSubset(of:b) a是不是b的子集合
  • a.isSuperset(of:b) b是不是a的子集合
  • a.isStrictSubset(of:b) a是不是b的子集合,并且b至少有一个元素不是a的元素。
  • a.isStrictSuperset(of:b) b是不是a的子集合,并且a至少有一个元素不是b的元素。
  • a.isDisjoint(with:b) a和b是否有相同的元素
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)

创建一个空字典

var namesOfIntegers = [Int: String]()
// namesOfIntegers is an empty [Int: String] dictionary

用字典语法创建字典

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

访问和修改字典

  • count属性获取字典内容的数量
print("The airports dictionary contains \(airports.count) items.")
// Prints "The airports dictionary contains 2 items.
  • isEmpty属性,是否count为0
if airports.isEmpty {
    print("The airports dictionary is empty.")
} else {
    print("The airports dictionary is not empty.")
}
// Prints "The airports dictionary is not empty.
  • 增加一对新的元素
airports["LHR"] = "London"
// the airports dictionary now contains 3 items
  • 修改对应key值的元素
airports["LHR"] = "London Heathrow"
// the value for "LHR" has been changed to "London Heathrow"

-updateValue(_:forKey:) 增加或修改对应key的值,如果旧值存在返回旧值,否则返回nil。

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

-removeValue(forKey:) 移除指定key的值,值存在返回对应的值,否则返回nil

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 (airportCode, airportName) in airports {
    print("\(airportCode): \(airportName)")
}
// YYZ: Toronto Pearson
// LHR: London Heathrow

分别遍历Key和值

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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容

  • 53.计算字符 在字符串中获取字符值的数量, 可以使用字符串字符属性中的计数属性: let unusualMena...
    无沣阅读 1,091评论 0 4
  • //var intArray:Array = [Int]();varintArray = [Int]();prin...
    XLsn0w阅读 436评论 0 0
  • 图中的哈萨克大娘一句汉话不会说,只能用手势交流,却帮我找到了遗失的钱包。再走和静,走在全国最大的县;走在全国第二大...
    一株行走的小草阅读 234评论 1 0
  • 我喝咖啡也是近两年的事儿,以前不敢喝,受不了,心跳过速太难受了!我这个人,天生心跳就慢,正常的时候每分钟...
    北墨猫小渔阅读 473评论 0 1
  • 七月份,一年又过半。 打开朋友圈,似乎都在不约而同的说着同样的话:“愿我们上半年所有的遗憾,都是下半年所有惊喜的铺...
    小苜蓿阅读 390评论 2 4