Swift語言是一個新的編程語言,用於iOS, macOS, watchOS, 和 tvOS的開發,不過Swift很多部分內容,我們可以從C或者Objective-C的開發經驗獲得一種熟悉感。Swift提供很多基礎類型,如Int,String,Double,Bool等類型,它和Objective-C的相關類型對應,不過他是值類型,而Objective-C的基礎類型是引用類型,另外Swift還提供了幾個集合類型,如Array
, Set
, 和 Dictionary;Swift引入一些Objective-C里面沒有的元祖類型,這個在C#里倒是有類似的,也是這個名詞。 Swift語言是一種類型安全的強類型語言,不是類似JavaScript的弱類型,能夠在提供開發效率的同時,減少常規出錯的可能,使我們在開發階段盡量發現一些類型轉換的錯誤並及時處理。
常量和變量
let maximumNumberOfLoginAttempts = 10 var currentLoginAttempt = 0
常量用let定義,變量用var定義,它們均可以通過自動推導類型,如上面的就是指定為整形的類型。
也可以通過逗號分開多個定義,如下所示
var x = 0.0, y = 0.0, z = 0.0
如果我們的變量沒有初始化值來確定它的類型,我們可以通過指定類型來定義變量,如下所示
var welcomeMessage: String var red, green, blue: Double
變量的打印,可以在輸出字符串中用括號包含變量輸出,括號前加斜杠 \ 符號。
print(friendlyWelcome) // Prints "Bonjour!" print("The current value of friendlyWelcome is \(friendlyWelcome)") // Prints "The current value of friendlyWelcome is Bonjour!"
注釋符
// This is a comment. /* This is also a comment but is written over multiple lines. */ /* This is the start of the first multiline comment. /* This is the second, nested multiline comment. */ This is the end of the first multiline comment. */
上面分別是常規的的注釋,以及Swift支持嵌套的注釋符號
分號
Swift語句的划分可以不用分號,不過你加分號也可以,如果加分號,則可以多條語句放在一行。
let cat = "🐱"; print(cat)
整型
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
一般情況下,我們不需要指定具體的Int類型,如Int32,Int64,我們一般采用int類型即可,這樣可以在不同的系統平台有不同的意義。
在32位平台,Int代表是Int32
在64位平台,Int代表Int64
浮點數字
Swift的浮點數字類型包括有Float(單精度)和Double(雙精度)兩個類型,Float代表32位浮點數字,Double代表64位浮點數字。
默認通過小數值推導的變量或者常量的類型是Double,而非Float。
數字文字
let decimalInteger = 17 let binaryInteger = 0b10001 // 17 二進制 let octalInteger = 0o21 // 17 八進制 let hexadecimalInteger = 0x11 // 17 十六進制
let decimalDouble = 12.1875 let exponentDouble = 1.21875e1 //科學計數法 1.21875*10 let hexadecimalDouble = 0xC.3p0 // p0代表 2的0次方
上面是科學計數方式的幾種方式
let paddedDouble = 000123.456 let oneMillion = 1_000_000 let justOverOneMillion = 1_000_000.000_000_1
上面是使用0代替補齊簽名數字,以及下划線來標識數字分割,方便閱讀
let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine
常量 three 初始化位整形類型, pointOneFourOneFiveNine 推導為Double類型,而pi則通過Double轉換推導為Double類型,這樣右邊兩個都是Double類型,可以進行相加的運算處理了。
布爾類型
let orangesAreOrange = true let turnipsAreDelicious = false
這個沒有什么好講的,就是語言默認有布爾類型提供,相對於Objective-C的非0則為True而言,布爾類型只有兩個字,True或者False。
布爾類型可以用於條件判斷等處理,如下
if turnipsAreDelicious { print("Mmm, tasty turnips!") } else { print("Eww, turnips are horrible.") }
元祖類型
元祖類型就是組合多個值的一個對象類型,在組合中的類型可以是任何Swift的類型,而且不必所有的值為相同類型。
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)")
元祖對象里面的值可以通過數字索引來引用,如0,1的屬性,如下
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"
可空類型
這個和C#里面的可空類型是對應的,也就是對象可能有值,也可能沒有值
let possibleNumber = "123" let convertedNumber = Int(possibleNumber) // convertedNumber 推導類型為 "Int?", 或者 "optional Int"
Int類型的構造函數為可空構造函數,有可能轉換失敗,因此返回的為可空Int類型
可空類型可以通過設置nil,來設置它為無值狀態
var serverResponseCode: Int? = 404 // serverResponseCode contains an actual Int value of 404 serverResponseCode = nil // serverResponseCode now contains no value
對於可空類型,如果確認它的值非空,那么可以強行解構它的值對象,訪問它的值在變量后面增加一個!符號,如下所示
if convertedNumber != nil { print("convertedNumber has an integer value of \(convertedNumber!).") }
一般情況下,我們可以通過可空綁定的方式來處理這種對象的值,語句語法如下所示
if let constantName = someOptional { statements }
具體的語句如下所示
if let actualNumber = Int(possibleNumber) { print("\"\(possibleNumber)\" has an integer value of \(actualNumber)") } else { print("\"\(possibleNumber)\" could not be converted to an integer") } // Prints ""123" has an integer value of 123"
也可以多個let的可空綁定語句一起使用
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") } } } // Prints "4 < 42 < 100"
解包可空類型可以通過!符號進行處理,一般情況如下所示進行判斷
let possibleString: String? = "An optional string." let forcedString: String = possibleString! // requires an exclamation mark let assumedString: String! = "An implicitly unwrapped optional string." let implicitString: String = assumedString // no need for an exclamation mark
也可以使用可空綁定的let 語句進行隱式的解包,如下所示
if let definiteString = assumedString { print(definiteString) } // Prints "An implicitly unwrapped optional string."
錯誤處理
函數拋出異常,通過在函數里面使用throws進行聲明,如下
func canThrowAnError() throws { // this function may or may not throw an error }
捕捉函數拋出的異常代碼如下
do { try canThrowAnError() // no error was thrown } catch { // an error was thrown }
詳細的案例代碼如下所示
func makeASandwich() throws { // ... } do { try makeASandwich() eatASandwich() } catch SandwichError.outOfCleanDishes { washDishes() } catch SandwichError.missingIngredients(let ingredients) { buyGroceries(ingredients) }
斷言調試
Swift提供一些標准庫函數來進行斷言調試,分為斷言和預設條件的處理兩部分。
斷言調試僅僅在Debug調試模式運行,而預設條件則是調試模式和產品發布后都會運行的。
let age = -3 assert(age >= 0, "A person's age can't be less than zero.") // This assertion fails because -3 is not >= 0.
if age > 10 { print("You can ride the roller-coaster or the ferris wheel.") } else if age > 0 { print("You can ride the ferris wheel.") } else { assertionFailure("A person's age can't be less than zero.") }
預設條件代碼如下,用來對一些條件進行校驗
// In the implementation of a subscript... precondition(index > 0, "Index must be greater than zero.")