基础部分
Swift的类型是在C和Objective-C的基础上改进,Int是整型,Double和Float是浮点型,Bool是布尔型,String是字符串,Array和Dictionary是集合,还有一些其他语言没有的比如元组,元组可以创建或传递一组数据,比如作为函数的返回值,可以用元组来返回多个值
Swift增加了可选类型(Optional),用于处理值的缺省情况,类似OC中的nil,可以用在任何类型上,不仅是类
Swift是一个类型安全的语言,可选(Optional)就是很好的例子,可让你清楚的知道一个值的类型,如果期望得到一个String,类型安全会阻止你以外的传入一个Int,并且可以在开发的时候就发现这种错误
let maximumNumberOfLoginAttempts = 10
var currentLoginAttempt = 0
以上例子中,看定义的名称大约也可以猜出来是什么意思了,定义一个不可变的常量,表示最大的登录尝试次数,定义一个变量,表示当前已经尝试过的登录次数
var x = 0.0, y = 0.0, z = 0.0
var welcomeMessage: String
然后这个字符串变量又可以随意赋其他的值了
welcomeMessage = "Hello"
一般来说添加类型注释是比较少用的,如果你在定义的时候提供了一个初始值,那编译器就会识别定义的变量或常量的类型,而不需要再指定
let π = 3.14159
let 你好 = "你好世界"
虽然说可以使用unicode来定义,但也要遵守一些规则,不能使用数学运算符,箭头,代码点还有一些什么畸形的符号什么的(保留的或非法的Unicode码),也不能以数字开头
一旦确定了一个常量或变量的类型,就不能再用相同的名字再定义了,或存储不同类型的值,也不能把变量改为常量,也不能把常量改为变量var friendlyWelcome = "Hello!"
friendlyWelcome = "Bonjour!"
// friendlyWelcome is now "Bonjour!"
let languageName = "Swift"
languageName = "Swift++"
// this is a compile-time error - languageName cannot be changed
使用println方法打印,就像Objective-C里的NSLog,使用反斜线和小括号显示变量
println("This is a string")
println("The current value of friendlyWelcome is \(friendlyWelcome)")
注释,跟其他类型语言的注释一样,自己体会
// this is a comment
/* this is also a comment,
but 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 */
分号,分号在这里已经不是必须的了,不过也要分清场合,如果你要在一行写多个语句,分号就不能省了
let cat = "cat"; println(cat)
整数范围
访问不同类型的min和max属性来获取相应类型的最小和最大值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
Swift提供一个特殊的整数类型Int,长度根据当前系统的字长相同,不需专门指定,在32位平台上,Int长度和Int32相同,在64位平台上,Int长度和Int64相同,Int32的存储范围为 -2147483648~2147483647UInt
无符号类型,但尽量不要用,除非真的需要存储一个跟当前平台字长相同的无符号整数,推荐使用Int浮点数
有小数部分的数字,浮点类型比整数类型表示的范围更大,Swfit有两种:Double,表示64位浮点数,精度至少有15位,当需要存储很大或者精度很高的浮点数时使用,Float,表示32位浮点数,只有6为数字的精度let meaningOfLife = 42
// meaningOfLife is inferred to be of type Int
如果没有给浮点数标明类型,Swift会推出类型是Double,当推测浮点数时,优选选择Double而不是Float
let pi = 3.14159
// pi is inferred to be of type Double
let anotherPi = 3 + 0.14159
// anotherPi is also inferred to be of type Double
let decimalInteger = 17
let binaryInteger = 0b10001 // 17 in binary notation
let octalInteger = 0o21 // 17 in octal notation
let hexadecimalInteger = 0x11 // 17 in hexadecimal notation
Integer Conversion整数的转换
每种数值类型能表示的数字范围是不一样的,Int8能表示的范围是-128到127之间,UInt8能表示的范围为0到255之间,如果赋的值与数值类型不一致将会在编译的时候报错
let cannotBeNegative: UInt8 = -1
// UInt8 cannot store negative numbers, and so this will report an error
let tooBig: Int8 = Int8.max + 1
// Int8 cannot store a number larger than its maximum value,
// and so this will also report an error
因为每个数值类型都可以存储不同范围的值,所以必须在转换的时候指定一个数值类型,以防止转换错误
let twoThousand: UInt16 = 2_000
let one: UInt8 = 1
let twoThousandAndOne = twoThousand + UInt16(one)
let three = 3
let pointOneFourOneFiveNine = 0.14159
let pi = Double(three) + pointOneFourOneFiveNine
// pi equals 3.14159, and is inferred to be of type Double
在这里,3由Int型转换为Double型,这样两种类型相同才能相加,否则编译不通过
let integerPi = Int(pi)
// integerPi equals 3, and is inferred to be of type Int
类似linux中的alias,可以给类型取别名,给类型取别名后就可以直接使用它的属性
typealias AudioSample = UInt16
var maxAmplitudeFound = AudioSample.min
// maxAmplitudeFound is now 0
let orangesAreOrange = true
let turnipsAreDelicious = false
if turnipsAreDelicious {
println("Mmm, tasty turnips!")
} else {
println("Eww, turnips are horrible.")
}
// prints "Eww, turnips are horrible."
let i = 1
if i {
// this example will not compile, and will report an error
}
let i = 1
if i == 1 {
// this example will compile successfully
}
let http404Error = (404, "Not Found")
// http404Error is of type (Int, String), and equals (404, "Not Found")
let (statusCode, statusMessage) = http404Error
println("The status code is \(statusCode)")
// prints "The status code is 404"
println("The status message is \(statusMessage)")
// prints "The status message is Not Found"
如果元组内有值没有用到,用下划线 _ 来省略
let (justTheStatusCode, _) = http404Error
println("The status code is \(justTheStatusCode)")
// prints "The status code is 404"
也可以使用下标代替元组的值,下标从0开始
println("The status code is \(http404Error.0)")
// prints "The status code is 404"
println("The status message is \(http404Error.1)")
// prints "The status message is Not Found"
在定义元组的同时就把名字给取好了,取值的时候就是元组加属性了
let http200Status = (statusCode: 200, description: "OK")
println("The status code is \(http200Status.statusCode)")
// prints "The status code is 200"
println("The status message is \(http200Status.description)")
// prints "The status message is OK"
作为函数返回值,元组非常有用,相比只能返回一个类型的值比起来,元组能让函数返回值更丰富
let possibleNumber = "123"
let convertedNumber = possibleNumber.toInt()
// convertedNumber is inferred to be of type "Int?", or "optional Int"
if convertedNumber {
println("\(possibleNumber) has an integer value of \(convertedNumber!)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"
if let constantName = someOptional {
statements
}
以下可理解为:如果possibleNumber.toInt 返回的可选值Int包含一个值,则新建一个actualNumber的常量并赋值给他,actualNumber的值可在if语句中使用,并且已经初始化,不需要用 ! 来取值
if let actualNumber = possibleNumber.toInt() {
println("\(possibleNumber) has an integer value of \(actualNumber)")
} else {
println("\(possibleNumber) could not be converted to an integer")
}
// prints "123 has an integer value of 123"
var serverResponseCode: Int? = 404
// serverResponseCode contains an actual Int value of 404
serverResponseCode = nil
// serverResponseCode now contains no value
var surveyAnswer: String?
// surveyAnswer is automatically set to nil
Swift中的nil和OC中的nil并不一样,在OC中,nil是一个指向空对象的指针,在Swift中,nil是一个确定的值,表示值的缺失,任何类型都可以赋值为nil
let possibleString: String? = "An optional string."
println(possibleString!) // requires an exclamation mark to access its value
// prints "An optional string."
let assumedString: String! = "An implicitly unwrapped optional string."
println(assumedString) // no exclamation mark is needed to access its value
// prints "An implicitly unwrapped optional string."
let age = -3
assert(age >= 0, "A person's age cannot be less than zero")
// this causes the assertion to trigger, because age is not >= 0