「Swift」笔记第一章:The Basic
1 第一章:基礎(chǔ)
- 提供C/OC所有基礎(chǔ)數(shù)據(jù)類型:int,double,float,string,bool;還提供三種基礎(chǔ)存儲(chǔ)數(shù)據(jù)的結(jié)構(gòu):array,set,dict,詳見Collection Types
- 引入了元組
- 引入可選類型
- 比較安全的語言,可以幫助明確代碼可以使用的值的類型
1.1 常量和變量
1.1.1 聲明常量和變量
1.1.2 類型注釋
1.1.3 命名變量和常量
1.1.4 打印常量和變量
1.2 注釋
- //
- /* */
- /* /* (內(nèi)嵌注釋)*/ */
1.3 分號(hào)作用
分割同一行中的多條命令:
let cat = "🐱"; print(cat)1.4 整數(shù)
Uint8 / Int32 等
以查看該類型能夠接收的數(shù)字的范圍let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8 let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8 這些屬性(UInt8.min)是適當(dāng)大小的值,因此可以與同類型的其他數(shù)據(jù)使用在表達(dá)式中
1.4.1 帶符號(hào)整數(shù):Int
1.4.2 無符號(hào)整數(shù):Uint
1.5 浮點(diǎn)數(shù)
1.6 類型安全和類型推斷
1.7 數(shù)字文本
A decimal number, with no prefix
A binary number, with a 0b prefix
An octal number, with a 0o prefix
A hexadecimal number, with a 0x prefix
1.8 數(shù)據(jù)類型轉(zhuǎn)換
1.8.1 整數(shù)轉(zhuǎn)換
- 可在表達(dá)式中對(duì)數(shù)據(jù)做類型轉(zhuǎn)換let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 let twoThousandAndOne = twoThousand + UInt16(one)
1.8.2 整數(shù)和浮點(diǎn)數(shù)的轉(zhuǎn)換
let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine // pi equals 3.14159, and is inferred to be of type Doublelet integerPi = Int(pi) // integerPi equals 3, and is inferred to be of type Int // 正負(fù)數(shù)均往零方向取整 let integerPi = Int(pi) // integerPi equals 3, and is inferred to be of type Int1.9 類型別名
使用關(guān)鍵詞typealias對(duì)已存在的類型賦予別名
typealias AudioSample = UInt16有助于上下文理解
1.10 布爾值
let orangesAreOrange = true let turnipsAreDelicious = false- swift語言的類型安全不允許布爾值的隱式轉(zhuǎn)換:
但可以通過執(zhí)行判斷語句,由其返回的true/false來判斷是否進(jìn)入條件
1.11 元組
元組可以將不同數(shù)據(jù)類型的數(shù)據(jù)放在一起:
let http404Error = (404, "Not Found") // http404Error is of type (Int, String), and equals (404, "Not Found")分解元組的方式包括:
let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") // Prints "The status code is 404" print("The status message is \(statusMessage)") // Prints "The status message is Not Found"let (justTheStatusCode, _) = http404Error print("The status code is \(justTheStatusCode)") // Prints "The status code is 404"// 還可以通過下標(biāo)的方式取元組中的值 print("The status code is \(http404Error.0)") // Prints "The status code is 404" print("The status message is \(http404Error.1)") // Prints "The status message is Not Found"// 還可以給元組的每個(gè)元素添加自定義描述 let http200Status = (statusCode: 200, description: "OK") print("The status code is \(http200Status.statusCode)") // Prints "The status code is 200" print("The status message is \(http200Status.description)") // Prints "The status message is OK"1.12 可選項(xiàng)(Optionals)
當(dāng)一個(gè)傳遞來的值可能是缺失時(shí),可以用optional進(jìn)行存儲(chǔ),optional表示接收的值存在/不存在
例如,當(dāng)對(duì)字符串轉(zhuǎn)整數(shù)時(shí),可能會(huì)轉(zhuǎn)換失敗:
此時(shí)convertedNumber的數(shù)據(jù)類型是“Int?”,而不是Int
1.12.1 nil
- var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
變量或非可選常量不能被賦值為nil,所以當(dāng)一個(gè)變量存儲(chǔ)的值可能缺失時(shí),一定要用optinal
-
如果帶optional的變量沒有初始化,那么系統(tǒng)會(huì)自動(dòng)賦予nill:
var surveyAnswer: String? // surveyAnswer is automatically set to nil
1.12.2 if聲明和強(qiáng)制展開
- 可以用if表達(dá)式判斷變量中是否有值:if convertedNumber != nil {print("convertedNumber contains some integer value.") } // Prints "convertedNumber contains some integer value." 如果有,可以通過!調(diào)用:if convertedNumber != nil {print("convertedNumber has an integer value of \(convertedNumber!).") } // Prints "convertedNumber has an integer value of 123." 此時(shí)如果convertedNumber含有值,由于convertedNumber是optinal類型,則用!對(duì)convertedNumber中的值進(jìn)行強(qiáng)制提取(forced Unwrapping)
1.12.3 可選綁定(Optinal Binding)
-
通過可選綁定,可以查找一個(gè)optianl值是否含有實(shí)值,如果有,則將其含有的值作為臨時(shí)常量或者變量。可以通過if或while判斷optinal是否含有值和提取:
if let constantName = someOptional {statements }利用Optinal的優(yōu)勢(shì),例如:
let possibleNumber = "123"if let actualNumber = Int(possibleNumber) {print("The string \"\(possibleNumber)\" has an integer value of \(actualNumber)") } else {print("The string \"\(possibleNumber)\" couldn't be converted to an integer") } // Prints "The string "123" has an integer value of 123"也可以將actualNumber用變量(var)的方式進(jìn)行申明
optinal和if的表達(dá)式還可以結(jié)合使用,if條件判斷中的并列表達(dá)式bool結(jié)果取交集
if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100") } // Prints "4 < 42 < 100"if let firstNumber = Int("4") {if let secondNumber = Int("42") {if firstNumber < secondNumber && secondNumber < 100 {print("\(firstNumber) < \(secondNumber) < 100")}} }
1.12.4 隱式展開的可選項(xiàng)
-
當(dāng)經(jīng)過程序某一過程后,一個(gè)optinal值在后續(xù)的程序中可以確定一定包含實(shí)值時(shí),可以將optinal確認(rèn)是否含值和展開過程省略。下面的代碼顯示了optinal和optinal隱式展開的區(qū)別:
let possibleString: String? = "An optional string." // 聲明一個(gè)可選項(xiàng) let forcedString: String = possibleString! // 將可選項(xiàng)內(nèi)的值強(qiáng)制解包,賦給forcedString,不加!會(huì)報(bào)錯(cuò),此時(shí)forcedString的類型為Stringlet assumedString: String! = "An implicitly unwrapped optional string." // 聲明一個(gè)隱式展開的可選項(xiàng) let implicitString: String = assumedString // 不再需要!來強(qiáng)制解包let optionalString = assumedString // 如果申明變量時(shí)沒有指出optinalString的類型,則被賦值時(shí)的類型還是optinal // The type of optionalString is "String?" and assumedString isn't force-unwrapped.
1.13 錯(cuò)誤處理
使用錯(cuò)誤處理來應(yīng)對(duì)程序中可能出現(xiàn)的錯(cuò)誤情況
首先需要在定義函數(shù)時(shí),使用關(guān)鍵字throw表明一個(gè)函數(shù)可能報(bào)錯(cuò):
func canThrowAnError() throws {// this function may or may not throw an error }然后使用do{}catch{}...catch{}..結(jié)構(gòu)來捕捉函數(shù)可能出現(xiàn)的錯(cuò)誤:
do {try canThrowAnError()// no error was thrown } catch {// an error was thrown } catch {... } ... // 一個(gè)例子: func makeASandwich() throws {// ... }do {try makeASandwich()eatASandwich() } catch SandwichError.outOfCleanDishes {washDishes() } catch SandwichError.missingIngredients(let ingredients) {buyGroceries(ingredients) }1.14 斷言和先決條件
斷言和先決條件是程序運(yùn)行過程中的檢查手段,用于確保程序執(zhí)行前,判斷基本條件是否滿足,假設(shè)滿足則返回true,繼續(xù)執(zhí)行之后的程序;如果不滿足,則終止程序/app的運(yùn)行。
總結(jié)
以上是生活随笔為你收集整理的「Swift」笔记第一章:The Basic的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「MacOS」无法打开***,因为无法验
- 下一篇: 什么是电子承兑汇票怎么使用