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定義,它們都可以經過自動推導類型,如上面的就是指定爲整形的類型。swift
也能夠經過逗號分開多個定義,以下所示安全
var x = 0.0, y = 0.0, z = 0.0
若是咱們的變量沒有初始化值來肯定它的類型,咱們能夠經過指定類型來定義變量,以下所示app
var welcomeMessage: String var red, green, blue: Double
變量的打印,能夠在輸出字符串中用括號包含變量輸出,括號前加斜槓 \ 符號。less
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語句的劃分能夠不用分號,不過你加分號也能夠,若是加分號,則能夠多條語句放在一行。ide
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表明是Int32ui
在64位平臺,Int表明Int64this
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.")