Swift--基本数据类型(二)

Booleans

Swift有主要的Boolean 类型,叫做Bool. 布尔值被称为逻辑运算,由于他们仅仅能是true或者false.Swift提供2种Boolean值,一个true,还有一个当然是false:

.    1  let orangesAreOrange= true

.    2  let turnipsAreDelicious= false

 

orangesAreOrangeturnipsAreDelicious已经在初始化的时候被定义为布尔值.对于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状态代码是返回的Webserver当你请求一个网页的特殊值。假设你请求的网页不存在则返回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"

 

 

posted on 2019-05-04 17:53  xfgnongmin  阅读(239)  评论(0编辑  收藏  举报

导航