「Swift」笔记第一章:The Basic
1 第一章:基礎
- 提供C/OC所有基礎數據類型:int,double,float,string,bool;還提供三種基礎存儲數據的結構:array,set,dict,詳見Collection Types
- 引入了元組
- 引入可選類型
- 比較安全的語言,可以幫助明確代碼可以使用的值的類型
1.1 常量和變量
1.1.1 聲明常量和變量
1.1.2 類型注釋
1.1.3 命名變量和常量
1.1.4 打印常量和變量
1.2 注釋
- //
- /* */
- /* /* (內嵌注釋)*/ */
1.3 分號作用
分割同一行中的多條命令:
let cat = "🐱"; print(cat)1.4 整數
Uint8 / Int32 等
以查看該類型能夠接收的數字的范圍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)是適當大小的值,因此可以與同類型的其他數據使用在表達式中
1.4.1 帶符號整數:Int
1.4.2 無符號整數:Uint
1.5 浮點數
1.6 類型安全和類型推斷
1.7 數字文本
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 數據類型轉換
1.8.1 整數轉換
- 可在表達式中對數據做類型轉換let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 let twoThousandAndOne = twoThousand + UInt16(one)
1.8.2 整數和浮點數的轉換
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 // 正負數均往零方向取整 let integerPi = Int(pi) // integerPi equals 3, and is inferred to be of type Int1.9 類型別名
使用關鍵詞typealias對已存在的類型賦予別名
typealias AudioSample = UInt16有助于上下文理解
1.10 布爾值
let orangesAreOrange = true let turnipsAreDelicious = false- swift語言的類型安全不允許布爾值的隱式轉換:
但可以通過執行判斷語句,由其返回的true/false來判斷是否進入條件
1.11 元組
元組可以將不同數據類型的數據放在一起:
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"// 還可以通過下標的方式取元組中的值 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"// 還可以給元組的每個元素添加自定義描述 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 可選項(Optionals)
當一個傳遞來的值可能是缺失時,可以用optional進行存儲,optional表示接收的值存在/不存在
例如,當對字符串轉整數時,可能會轉換失敗:
此時convertedNumber的數據類型是“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,所以當一個變量存儲的值可能缺失時,一定要用optinal
-
如果帶optional的變量沒有初始化,那么系統會自動賦予nill:
var surveyAnswer: String? // surveyAnswer is automatically set to nil
1.12.2 if聲明和強制展開
- 可以用if表達式判斷變量中是否有值:if convertedNumber != nil {print("convertedNumber contains some integer value.") } // Prints "convertedNumber contains some integer value." 如果有,可以通過!調用:if convertedNumber != nil {print("convertedNumber has an integer value of \(convertedNumber!).") } // Prints "convertedNumber has an integer value of 123." 此時如果convertedNumber含有值,由于convertedNumber是optinal類型,則用!對convertedNumber中的值進行強制提取(forced Unwrapping)
1.12.3 可選綁定(Optinal Binding)
-
通過可選綁定,可以查找一個optianl值是否含有實值,如果有,則將其含有的值作為臨時常量或者變量??梢酝ㄟ^if或while判斷optinal是否含有值和提取:
if let constantName = someOptional {statements }利用Optinal的優勢,例如:
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)的方式進行申明
optinal和if的表達式還可以結合使用,if條件判斷中的并列表達式bool結果取交集
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 隱式展開的可選項
-
當經過程序某一過程后,一個optinal值在后續的程序中可以確定一定包含實值時,可以將optinal確認是否含值和展開過程省略。下面的代碼顯示了optinal和optinal隱式展開的區別:
let possibleString: String? = "An optional string." // 聲明一個可選項 let forcedString: String = possibleString! // 將可選項內的值強制解包,賦給forcedString,不加!會報錯,此時forcedString的類型為Stringlet assumedString: String! = "An implicitly unwrapped optional string." // 聲明一個隱式展開的可選項 let implicitString: String = assumedString // 不再需要!來強制解包let optionalString = assumedString // 如果申明變量時沒有指出optinalString的類型,則被賦值時的類型還是optinal // The type of optionalString is "String?" and assumedString isn't force-unwrapped.
1.13 錯誤處理
使用錯誤處理來應對程序中可能出現的錯誤情況
首先需要在定義函數時,使用關鍵字throw表明一個函數可能報錯:
func canThrowAnError() throws {// this function may or may not throw an error }然后使用do{}catch{}...catch{}..結構來捕捉函數可能出現的錯誤:
do {try canThrowAnError()// no error was thrown } catch {// an error was thrown } catch {... } ... // 一個例子: func makeASandwich() throws {// ... }do {try makeASandwich()eatASandwich() } catch SandwichError.outOfCleanDishes {washDishes() } catch SandwichError.missingIngredients(let ingredients) {buyGroceries(ingredients) }1.14 斷言和先決條件
斷言和先決條件是程序運行過程中的檢查手段,用于確保程序執行前,判斷基本條件是否滿足,假設滿足則返回true,繼續執行之后的程序;如果不滿足,則終止程序/app的運行。
總結
以上是生活随笔為你收集整理的「Swift」笔记第一章:The Basic的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 「MacOS」无法打开***,因为无法验
- 下一篇: 「Anaconda」取消终端命令行自动加