- 別名:typealias
typealias AudioSample = UInt16
// AudioSample 被定義為 UInt16 的一個(gè)別名
var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound 現(xiàn)在是 0
- 元組:(,,...)
let http404Error = (404, "Not Found","next")
// http404Error 的類(lèi)型是 (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"
- 可選類(lèi)型:?
var serverResponseCode: Int? = 404
// serverResponseCode 包含一個(gè)可選的 Int 值 404
serverResponseCode = nil
// serverResponseCode 現(xiàn)在不包含值
//
var surveyAnswer: String?
// surveyAnswer 被自動(dòng)設(shè)置為 nil,surveyAnswer的類(lèi)型要么為nil要么為String
- 隱式解析可選類(lèi)型:!
可選類(lèi)型被第一次賦值之后就可以確定之后一直有值
let possibleString: String? = "An optional string."
let forcedString: String = possibleString!
// 需要感嘆號(hào)來(lái)獲取值
let assumedString: String! = "An implicitly unwrapped optional string."
let implicitString: String = assumedString
// 不需要感嘆號(hào)
- 錯(cuò)誤處理:
func makeASandwich() throws {
// ...
}
do {
try makeASandwich()
eatASandwich()
} catch SandwichError.outOfCleanDishes {
washDishes()
} catch SandwichError.missingIngredients(let ingredients) {
buyGroceries(ingredients)
}
- 斷言:assert(...) 結(jié)束代碼運(yùn)行并通過(guò)調(diào)試來(lái)找到值缺失的原因。
let age = -3
assert(age >= 0, "A person's age cannot be less than zero") // 因?yàn)?age < 0,所以斷言會(huì)觸發(fā)
三目運(yùn)算符:?jiǎn)栴} ? T答案1 : F答案2
空合運(yùn)算符:a??b
a??b
//等價(jià)于
a != nil ? a! : b
/*
當(dāng)可選類(lèi)型 a 的值不為空時(shí),進(jìn)行強(qiáng)制解封(a!),訪問(wèn) a 中的值;
反之返 回默認(rèn)值 b 。
無(wú)疑空合運(yùn)算符( ?? )提供了一種更為優(yōu) 的方式
去封裝條件判斷和解封兩種行為,顯得簡(jiǎn)潔以及更具可讀性。
*/
let defaultColorName = "red"
var userDefinedColorName: String? //默認(rèn)值為 nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
// userDefinedColorName 的值為空,所以 colorNameToUse 的值為 "red"
- 字符串:用characters屬性獲取每個(gè)值
for character in "Dog!?".characters {
print(character)
}
// D
// o
// g
// !
// ?
可傳遞一個(gè)值類(lèi)型為 Character 的數(shù)組作為自變量來(lái)初始化
let catCharacters: [Character] = ["C", "a", "t", "!", "?"]
let catString = String(catCharacters)
print(catString)
// 打印輸出:"Cat!?"
可以用 append() 方法將一個(gè)字符附加到一個(gè)字符串變量的尾部
let exclamationMark: Character = "!"
welcome.append(exclamationMark)
// welcome 現(xiàn)在等于 "hello there!"
字符串插值: \ (...) 用于構(gòu)建新字符串
let multiplier = 3
let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)"
// message 是 "3 times 2.5 is 7.5"
你可以使用下標(biāo)語(yǔ)法來(lái)訪問(wèn) String 特定索引的 Character 。
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// G (第一個(gè)索引)
greeting[greeting.index(before: greeting.endIndex)]
// !(最后一個(gè)索引的前一個(gè)索引)
greeting[greeting.index(after: greeting.startIndex)]
// u(第一個(gè)索引的后一個(gè)索引)
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// a(第一個(gè)索引后7個(gè)的索引)
greeting[greeting.endIndex]
// error
greeting.index(after: endIndex)
// error
使用 characters 屬性的 indices 屬性會(huì)創(chuàng)建一個(gè)包含全部索引的范圍(Range),用來(lái)在一個(gè)字符串中訪問(wèn)單個(gè)字符。
for index in greeting.characters.indices {
print("\(greeting[index]) ", terminator: "")
//terminator用字符串取代換行
}
// 打印輸出 "G u t e n T a g ! "
插入和刪除:
調(diào)用 insert(_:at:) 方法可以在一個(gè)字符串的指定索引插入一個(gè)字符
調(diào)用 insert(contentsOf:at:) 方法可以在一個(gè)字符串的指定索引插入一個(gè)段字符串。
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex) // welcome 變量現(xiàn)在等于 "hello!"
welcome.insert(contentsOf:" there".characters, at: welcome.index(before: welcome.endIndex)) // welcome 變量現(xiàn)在等于 "hello there!"
調(diào)用 remove(at:) 方法可以在一個(gè)字符串的指定索引刪除一個(gè)字符
調(diào)用 removeSubrange(_:) 方法可以在一 個(gè)字符串的指定索引刪除一個(gè)子字符串。
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome 現(xiàn)在等于 "hello there"
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex welcome.removeSubrange(range)
// welcome 現(xiàn)在等于 "hello"
Unicode是一個(gè)國(guó)際標(biāo)準(zhǔn),用于文本的編碼和表示。
它使您可以用標(biāo)準(zhǔn)格式表示來(lái)自任意語(yǔ)言幾乎所有的字符,
并能夠?qū)ξ谋疚募蚓W(wǎng)頁(yè)這樣的外部資源中的字符進(jìn)行讀寫(xiě)操作。Swift 語(yǔ)言提供 Arrays、Sets和Dictionaries三種基本的合類(lèi)型用來(lái)存儲(chǔ)合數(shù)據(jù)。
數(shù)組(Arrays)是有序數(shù)據(jù)的。
集合(Sets)是無(wú)序無(wú)重復(fù)數(shù)據(jù)的。
字典(Dictionaries)是無(wú)序的鍵值對(duì)的。
Arrays 、 Sets 和 Dictionaries 類(lèi)型被實(shí)現(xiàn)為泛型集合。
存儲(chǔ)的數(shù)據(jù)類(lèi)型必須明確Array數(shù)組:使用有序列表存儲(chǔ)同一類(lèi)型的多個(gè)值。
例:字符串?dāng)?shù)組
var shoppingList: [String] = ["Eggs", "Milk"]
var shoppingList = ["Eggs", "Milk"]
// shoppingList 已經(jīng)被構(gòu)造并且擁有兩個(gè)初始項(xiàng)。
shoppingList.append("Flour")
// shoppingList 現(xiàn)在追加了第3個(gè)數(shù)據(jù)項(xiàng),有人在攤煎餅
shoppingList += ["Baking Powder"]
// shoppingList 現(xiàn)在有四項(xiàng)了
shoppingList += ["Chocolate Spread", "Cheese", "Butter"]
// shoppingList 現(xiàn)在有七項(xiàng)了
var firstItem = shoppingList[0]
// 第一項(xiàng)是 "Eggs"
shoppingList[0] = "Six eggs"
// 其中的第一項(xiàng)現(xiàn)在是 "Six eggs" 而不是 "Eggs"
shoppingList[4...6] = ["Bananas", "Apples"]
//下標(biāo)為4到6 替換成Bananas和Apples 現(xiàn)在有6項(xiàng)
shoppingList.insert("Maple Syrup", at: 0)
// shoppingList 現(xiàn)在有7項(xiàng)
// 在下標(biāo)為0前添加"Maple Syrup"
let mapleSyrup = remove(at: 0)
// 索引值為0的數(shù)據(jù)項(xiàng)被移除
// shoppingList 現(xiàn)在只有6項(xiàng),而且不包括 Maple Syrup
// mapleSyrup 常量的值等于被移除數(shù)據(jù)項(xiàng)的值 "Maple Syrup"
let apples = shoppingList.removeLast()
// 數(shù)組的最后一項(xiàng)被移除了
// shoppingList 現(xiàn)在只有5項(xiàng),不包括 Apples
// apples 常量的值現(xiàn)在等于 "Apples" 字符串
//
//數(shù)組的遍歷:
for item in shoppingList {
print(item)
}
// Six eggs
// Milk
// Flour
// Baking Powder
// Bananas
//
//數(shù)組元組遍歷
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集合:用來(lái)存儲(chǔ)相同類(lèi)型并且沒(méi)有確定順序的值。
var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"]
// favoriteGenres 被構(gòu)造成含有三個(gè)初始值的集合
print("I have \(favoriteGenres.count) favorite music genres.")
// 打印 "I have 3 favorite music genres."
favoriteGenres.insert("Jazz")
// favoriteGenres 現(xiàn)在包含4個(gè)元素
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."
//
/*
遍歷一個(gè)集合
*/
//1.for-in循環(huán)
for genre in favoriteGenres {
print("\(genre)")
}
// 無(wú)序:
// 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結(jié)合里 不在single集合里
oddDigits.subtracting(singleDigitPrimeNumbers).sorted()
// [1, 9]
//
//在oddDigits/single集合里 但不在并集合里
oddDigits. symmetricDifference(singleDigitPrimeNumbers).sorted()
// [1, 2, 9]
//
/*
集合成員關(guān)系:
*/
let houseAnimals: Set = ["?", "?"]
let farmAnimals: Set = ["?", "?", "?", "?", "?"]
let cityAnimals: Set = ["?", "?"]
//isSubset(of:) 方法來(lái)判斷一個(gè)集合中的值是否也被包含在另外一個(gè)集合中
houseAnimals.isSubset(of: farmAnimals)
// true
//isSuperset(of:) 方法來(lái)判斷一個(gè)集合中包含另一個(gè)集合中所有的值
farmAnimals.isSuperset(of: houseAnimals)
// true
//isStrictSubset(of:) 或者 isStrictSuperset(of:) 方法來(lái)判斷一個(gè)集合是否是另外一個(gè)集合的子集合或者父集合并且兩個(gè)集合并不相等
//
//isDisjoint(with:) 方法來(lái)判斷兩個(gè)集合是否不含有相同的值(是否沒(méi)有交集)
farmAnimals.isDisjoint(with: cityAnimals)
// true
- Dictionary字典:一種存儲(chǔ)多個(gè)相同類(lèi)型的值的容器。
每個(gè)值(value)都關(guān)聯(lián)唯一的鍵(key)
var namesOfIntegers = Int: String
// namesOfIntegers 是一個(gè)空的 [Int: String] 字典
namesOfIntegers[16] = "sixteen"
// namesOfIntegers 現(xiàn)在包含一個(gè)鍵值對(duì)
namesOfIntegers = [:]
// namesOfIntegers 又成為了一個(gè) [Int: String] 類(lèi)型的空字典
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
var airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
airports["LHR"] = "London"
// airports 字典現(xiàn)在有三個(gè)數(shù)據(jù)項(xiàng)
airports["LHR"] = "London Heathrow"
// "LHR"對(duì)應(yīng)的值 被改為 "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 機(jī)場(chǎng), 刪除它
airports["APL"] = nil
// APL 現(xiàn)在被移除了
//
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直接創(chuàng)建一個(gè)Array實(shí)例的API參數(shù)
let airportCodes = String
// airportCodes 是 ["YYZ", "LHR"]
let airportNames = String
// airportNames 是 ["Toronto Pearson", "London Heathrow"]