Swift--基本数据类型(二)
来源:互联网 发布:三坐标编程视频教程 编辑:程序博客网 时间:2024/04/29 12:33
Booleans
Swift有基本的Boolean 类型,叫做Bool. 布尔值被称为逻辑运算,因为他们只能是true或者false.Swift提供2种Boolean值,一个true,另一个当然是false:
. 1 letorangesAreOrange= true
. 2 letturnipsAreDelicious= 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--基本数据类型(二)
- Swift快速入门(二)基本数据类型
- 二 Swift 3.0之 基本数据类型
- Swift 基本数据类型--数据类型
- Swift--基本数据类型(一)
- swift基本数据类型
- swift 3. 基本数据类型
- [Swift]基本数据类型
- Swift基本数据类型
- swift语言-基本数据类型
- swift 基本数据类型--字符串
- swift 02 基本数据类型
- Swift基本数据类型
- swift:基本数据类型
- Swift-基本数据类型
- Swift中的基本数据类型
- 1.2 Swift基本数据类型
- swift学习---基本数据类型
- Apple Swift编程语言入门教程
- 函数模板的使用说明
- C#的Action<>和Func<>
- Android手机配合Fiddler抓包
- 学习SEO20天有感
- Swift--基本数据类型(二)
- 演示账号激活的过程:注册——>向指定邮箱发送邮件——>用户登录邮箱,激活账号
- java swing皮肤使用(substance)
- tomcat+java的web程序持续占cpu问题调试
- 查看不同语言的Manual
- 每天一个linux命令(3):pwd命令
- 早期收集的IOS各FRAME功能集
- greenplum安装配置等效性失败一例
- 在Unity3D中使用ScriptableObject进行序列化