Swift 该来的还是要来的,Swift使用范围越来越广,你不用,大家都会用,然后呢。。。你又落后了。。
常量变量
首先呢,每门语言都是从常量变量讲起,Swift当然也不例外
在Swift中常量 使用 let声明 变量使用var声明
不像OC或者Java 我们在声明常量变量时,可以不加类型,编译器能够帮助我们推断出类型,像这样
let myName = "Yang Qian"
var myAge = 23
在上面两行中,并没有指明 myAge 和 myName 的类型,编译器也没有报错,当然,我们也是可以声明他们的类型的:
let myName: String = "Yang Qian"
let myAge: Int = 23
let 🐶🐮 = "dogcow"
注意这里有一个书写规范,苹果在文档中特意提醒了,在声明类型的时候,需要在冒号后面空一格,保持格式一致。
常量(let)一旦声明,便不可更改。变量(var)可进行更改
注释
// This is a comment. 这是一行注释
/*
这是多行注释
*/
分号
关于分号呢,在Swift中,每个语句结束是不用写分号的,当然也可以写,但是我们推荐呢,还是不要写了,苹果都说不用写了,你还写干嘛,而且现在看一些开源的Swift代码,大神都没写分号。
但是存在一种情况,就是如果你想在一行写多个语句,那每个语句之间你就需要用分号隔开了
//这样就会报错了
let myName: String = "Yang Qian" let myAge: Int = 23
//要这样写
let myName: String = "Yang Qian" ; let myAge: Int = 23
这样的代码也太丑了吧,还是一行一个语句吧,养成良好的代码习惯
整数Int
在Swift上,提供了一个特殊的整数类型Int,在32位的机器上运行,那这个整数的长度就是和Int32相同,如果实在64为机器上运行,那这个整数的长度就是Int64的,一般来说 我们直接使用Int就已经OK了。
无类型UInt
无符号类型,一般呢我们不使用,为什么呢? 苹果文档上讲的
Use UInt only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case, Int is preferred, even when the values to be stored are known to be non-negative
类型别名
类型别名 就是给现有的类型加上一个我们自己自定义的名称 使用关键字 typealias定义
//这样,我们就将UInt16定义成了 AudioSample
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
// 等价于 var maxAmplitudeFound = UInt16.min
Booleans
现在我们的布尔值 不再是OC 中的 Yes 和 No 了 需要使用 true false
而且 现在呢,我们也不能再使用int的 0 1 来表示 true 或者false 了 之前呢 OC是可以这样使用的 但是在swift中,编译器就会报错了
let i = 1
if i {
// this example will not compile, and will report an error
}
这样,苹果讲了,是会报错的
Tuples 元组
元组,这个厉害了,这个可以把多个值组合成一个复合值,就是一个元组,而且这个元组里的各个值,不用类型相同,这下厉害了,这样一来,我们传参数,还有函数返回值,都可以多个了 想想 挺激动的 虽然还没用
let http404Error = (404, "Not Found")
上面,就是一个表示404 的一个元组,看到了,是一个404 Int 和 一个 String
let http404Code = (404, "Not Found")
let (statusCode, statusString) = http404Code
print("the code is \(statusCode)")
print("the message is \(statusString)")
输出:
the code is 404
the message is Not Found
如果呢,我们只关心我们需要的数据,不关心其他的,比如在上面的例子中,我们只关心code 那么我们就可以这样写
let http404Code = (404, "Not Found")
let (statusCode, _) = http404Code
print("the code is \(statusCode)")
//print("the message is \(statusString)")
输出
the code is 404
能少写一点是一点
还可以呢,像数组一样,输出元组的第几位:
let http404Code = (404, "Not Found")
print("the code is \(http404Code.0)")
print("the message is \(http404Code.1)")
输出呢,一样的:
the code is 404
the message is Not Found
别急 还有写法呢:
let http200Status = (statusCode: 200, description: "OK")
然后我们来输出:
print("The status code is \(http200Status.statusCode)")
// Prints "The status code is 200
简直太强大了,我个人最喜欢 那种点语法
