Swift 整理(三)——字符串、集合类型

  • 别名:typealias
typealias AudioSample = UInt16
// AudioSample 被定义为 UInt16 的一个别名
var maxAmplitudeFound = AudioSample.min 
// maxAmplitudeFound 现在是 0
  • 元组:(,,...)
let http404Error = (404, "Not Found","next")
// http404Error 的类型是 (Int, String,String),值是 (404, "Not Found","next")
//
//
let (statusCode, statusMessage,_) = http404Error
print("The status code is \(statusCode)")
// 输出 "The status code is 404"
print("The status message is \(statusMessage)") 
// 输出 "The status message is Not Found"
  • 可选类型:?
var serverResponseCode: Int? = 404
// serverResponseCode 包含一个可选的 Int 值 404
serverResponseCode = nil
// serverResponseCode 现在不包含值
//
var surveyAnswer: String?
// surveyAnswer 被自动设置为 nil,surveyAnswer的类型要么为nil要么为String
  • 隐式解析可选类型:!
    可选类型被第一次赋值之后就可以确定之后一直有值
let possibleString: String? = "An optional string."
let forcedString: String = possibleString! 
// 需要感叹号来获取值
let assumedString: String! = "An implicitly unwrapped optional string." 
let implicitString: String = assumedString 
// 不需要感叹号
  • 错误处理:
func makeASandwich() throws {
     // ...
}
 do {
     try makeASandwich()
     eatASandwich()
 } catch SandwichError.outOfCleanDishes {
     washDishes()
 } catch SandwichError.missingIngredients(let ingredients) {
     buyGroceries(ingredients)
}
  • 断言:assert(...) 结束代码运行并通过调试来找到值缺失的原因。
let age = -3
assert(age >= 0, "A person's age cannot be less than zero") // 因为 age < 0,所以断言会触发
  • 三目运算符:问题 ? T答案1 : F答案2

  • 空合运算符:a??b

a??b
//等价于
a != nil ? a! : b
/*
当可选类型 a 的值不为空时,进行强制解封(a!),访问 a 中的值;
反之返 回默认值 b 。
无疑空合运算符( ?? )提供了一种更为优 的方式
去封装条件判断和解封两种行为,显得简洁以及更具可读性。
*/
let defaultColorName = "red"
var userDefinedColorName: String? //默认值为 nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName 的值为空,所以 colorNameToUse 的值为 "red"
  • 字符串:用characters属性获取每个值
for character in "Dog!?".characters {
    print(character)
}
// D
// o
// g
// !
// ?

可传递一个值类型为 Character 的数组作为自变量来初始化

let catCharacters: [Character] = ["C", "a", "t", "!", "?"] 
let catString = String(catCharacters)
print(catString)
// 打印输出:"Cat!?"

可以用 append() 方法将一个字符附加到一个字符串变量的尾部

let exclamationMark: Character = "!" 
welcome.append(exclamationMark)
// welcome 现在等于 "hello there!"

字符串插值: \ (...) 用于构建新字符串

let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" 
// message 是 "3 times 2.5 is 7.5"

你可以使用下标语法来访问 String 特定索引的 Character 。

let greeting = "Guten Tag!"
 greeting[greeting.startIndex]
 // G (第一个索引)
 greeting[greeting.index(before: greeting.endIndex)]
 // !(最后一个索引的前一个索引)
 greeting[greeting.index(after: greeting.startIndex)]
 // u(第一个索引的后一个索引)
 let index = greeting.index(greeting.startIndex, offsetBy: 7)
 greeting[index]
 // a(第一个索引后7个的索引)
greeting[greeting.endIndex] 
// error
 greeting.index(after: endIndex) 
// error

使用 characters 属性的 indices 属性会创建一个包含全部索引的范围(Range),用来在一个字符串中访问单个字符。

 for index in greeting.characters.indices {
    print("\(greeting[index]) ", terminator: "")
//terminator用字符串取代换行
}
// 打印输出 "G u t e n T a g ! "

插入和删除:
调用 insert(_:at:) 方法可以在一个字符串的指定索引插入一个字符
调用 insert(contentsOf:at:) 方法可以在一个字符串的指定索引插入一个段字符串。

var welcome = "hello"
welcome.insert("!", at: welcome.endIndex) // welcome 变量现在等于 "hello!"
welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex)) // welcome 变量现在等于 "hello there!"

调用 remove(at:) 方法可以在一个字符串的指定索引删除一个字符
调用 removeSubrange(_:) 方法可以在一 个字符串的指定索引删除一个子字符串。

welcome.remove(at: welcome.index(before: welcome.endIndex))
 // welcome 现在等于 "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex welcome.removeSubrange(range)
// welcome 现在等于 "hello"
  • Unicode是一个国际标准,用于文本的编码和表示。
    它使您可以用标准格式表示来自任意语言几乎所有的字符,
    并能够对文本文件或网页这样的外部资源中的字符进行读写操作。

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

  • Array数组:使用有序列表存储同一类型的多个值。
    例:字符串数组

var shoppingList: [String] = ["Eggs", "Milk"] 
var shoppingList = ["Eggs", "Milk"]
// shoppingList 已经被构造并且拥有两个初始项。
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"
shoppingList[4...6] = ["Bananas", "Apples"] 
//下标为4到6 替换成Bananas和Apples 现在有6项
shoppingList.insert("Maple Syrup", at: 0) 
// shoppingList 现在有7项
// 在下标为0前添加"Maple Syrup" 
let mapleSyrup = remove(at: 0)
// 索引值为0的数据项被移除
// shoppingList 现在只有6项,而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除数据项的值 "Maple Syrup"
let apples = shoppingList.removeLast()
// 数组的最后一项被移除了
// shoppingList 现在只有5项,不包括 Apples 
// apples 常量的值现在等于 "Apples" 字符串
//
//数组的遍历:
 for item in shoppingList {
     print(item)
 }
 // Six eggs
 // Milk
 // Flour
 // Baking Powder
 // Bananas
//
//数组元组遍历
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
  • Set集合:用来存储相同类型并且没有确定顺序的值。
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] 
// favoriteGenres 被构造成含有三个初始值的集合
print("I have \(favoriteGenres.count) favorite music genres.") 
// 打印 "I have 3 favorite music genres."
favoriteGenres.insert("Jazz")
// favoriteGenres 现在包含4个元素
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."
//
 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."
//
/*
遍历一个集合
*/
//1.for-in循环
for genre in favoriteGenres {
     print("\(genre)")
 }
 // 无序:
 // Classical
 // Jazz
 // Hip hop
//
//for-in用sorted()方法
 for genre in favoriteGenres.sorted() {
     print("(genre)")
 }
// 有序:
 // prints "Classical"
 // prints "Hip hop"
 // prints "Jazz
//
 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. intersection(evenDigits).sorted()
 // []
//
//在oddDigits结合里 不在single集合里
 oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
 // [1, 9]
//
//在oddDigits/single集合里 但不在并集合里
 oddDigits. symmetricDifference(singleDigitPrimeNumbers).sorted()
 // [1, 2, 9]
//
/*
集合成员关系:
*/
 let houseAnimals: Set = ["?", "?"]
 let farmAnimals: Set = ["?", "?", "?", "?", "?"]
 let cityAnimals: Set = ["?", "?"]
//isSubset(of:) 方法来判断一个集合中的值是否也被包含在另外一个集合中
 houseAnimals.isSubset(of: farmAnimals)
 // true
//isSuperset(of:) 方法来判断一个集合中包含另一个集合中所有的值
 farmAnimals.isSuperset(of: houseAnimals)
 // true
//isStrictSubset(of:) 或者 isStrictSuperset(of:) 方法来判断一个集合是否是另外一个集合的子集合或者父集合并且两个集合并不相等
//
//isDisjoint(with:) 方法来判断两个集合是否不含有相同的值(是否没有交集)
 farmAnimals.isDisjoint(with: cityAnimals)
 // true
  • Dictionary字典:一种存储多个相同类型的值的容器。
    每个值(value)都关联唯一的键(key)
var namesOfIntegers = Int: String
// namesOfIntegers 是一个空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 现在包含一个键值对
namesOfIntegers = [:]
// namesOfIntegers 又成为了一个 [Int: String] 类型的空字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London"
// airports 字典现在有三个数据项
airports["LHR"] = "London Heathrow"
// "LHR"对应的值 被改为 "London Heathrow
 if let oldValue = airports.updateValue("Dublin Airport", forKey: "DUB") {
     print("The old value for DUB was (oldValue).")
}
// 输出 "The old value for DUB was Dublin."
//
 if let airportName = airports["DUB"] {
     print("The name of the airport is (airportName).")
 } else {
     print("That airport is not in the airports dictionary.")
}
// 打印 "The name of the airport is Dublin Airport."
airports["APL"] = "Apple Internation"
// "Apple Internation" 不是真的 APL 机场, 删除它 
airports["APL"] = nil
// APL 现在被移除了
//
 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."
//
/*
字典遍历:
*/
//1. for-in元组
for (airportCode, airportName) in airports {
     print("(airportCode): (airportName)")
 }
 // YYZ: Toronto Pearson
 // LHR: London Heathrow
//
//2.keys或value属性
 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
//
//用key或者value直接创建一个Array实例的API参数
let airportCodes = String
// airportCodes 是 ["YYZ", "LHR"]
let airportNames = String
// airportNames 是 ["Toronto Pearson", "London Heathrow"]
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容