Swift--基本数据类型(二)
Booleans
Swift有基本的Boolean 類型,叫做Bool. 布爾值被稱為邏輯運算,因為他們只能是true或者false.Swift提供2種Boolean值,一個true,另一個當然是false:
.??? 1 ?let orangesAreOrange= true
.??? 2 ?let turnipsAreDelicious= false
?
orangesAreOrange和turnipsAreDelicious已經在初始化的時候被定義為布爾值.對于Int和Double類型,你并不能在一開始初始化的時候就未他們設置為true或者fasle. 類型推斷有助于使Swift代碼更簡潔和可讀性,當它初始化為其它值,其類型是已知的常量或變量。
當你使用if語句時,布爾類型顯得尤為重要:
if turnipsAreDelicious {
??? println("Mmm, tasty turnips!")
}?else{
println("Eww, turnips are horrible.")
?
}
?//prints "Eww, turnips are horrible."
Swift的類型安全可以防止非布爾值被用于替代布爾
?leti=1
?ifi{
println("Eww, turnips are horrible.")
?
}
// thisexample will not compile, and will report an error
然而接下來的例子就是可行的:
?
?
leti=1
ifi==1{
}
// thisexample will compile successfully
?
i==1比較的結果為BOOL類型,所以這第二個例子通過類型檢查。
?
正如Swift類型安全的其他例子,這種方法避免了意外的錯誤,并確保代碼的特定部分的意圖始終是明確的。
?
Tuples
多元組可以是一個單一的值到多個值的復合值。元組中的值可以是任何類型的,并且不必須是相同的類型。
?
在這個例子中,(404,“Not Found”)是一個元組,它描述的HTTP狀態代碼。 HTTP狀態代碼是返回的Web服務器當你請求一個網頁的特殊值。如果你請求的網頁不存在則返回404狀態代碼未找到。
.??? let http404Error = (404,"Not Found")
.??? ?// http404Error is of type (Int, String),and equals (404, "Not Found")
在(404,“Not Found”)的元組組合在一起的詮釋和一個字符串給HTTP狀態代碼兩個獨立的價值:一個Int和一個String可讀的描述。它可以被描述為“類型的元組(Int,String)”。
你也可以創建更多的類型,(int,int,int)或者(Sting,Bool),你想怎么創造都可以.
對于多元組中的元素訪問和一般的元素訪問一樣:
.??? 1 ?let (statusCode, statusMessage)= http404Error
.??? 2 ?println("The status code is \(statusCode)")
.??? 3 ?// prints "The status code is404"
.??? 4 ?println("The status message is \(statusMessage)")
.??? 5 ?// prints "The status message is NotFound"
?
如果你只需要一些元組的值,忽略元組的部分用下劃線(_):
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
//prints "The status code is 404"
另外,在訪問使用從零開始的索引號的元組的各個元素的值:
.??? 1 ?println("The status code is \(http404Error.0)")
.??? 2 ?// prints "The status code is404"
.??? 3 ?println("The status message is \(http404Error.1)")
.??? 4 ?// prints "The status message is NotFound"
元組定義時可以命名一個元組的各個元素:
let http200Status = (statusCode:200, description:"OK")
如果你的名字在一個元組中的元素,你可以使用元素名稱來訪問這些元素的值:
.??? 1 ?println("The status code is \(http200Status.statusCode)")
.??? 2 ?// prints "The status code is200"
.??? 3 ?println("The status message is \(http200Status.description)")
.??? 4 ?// prints "The status message isOK"
?
?
總結
以上是生活随笔為你收集整理的Swift--基本数据类型(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微软发布Windows 11重大更新 将
- 下一篇: Swift--基本运算符