下载贤集网APP入驻自媒体
Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或者Objective-C的开发经验获得一种熟悉感。Swift提供很多基础类型,如Int,String,Double,Bool等类型,它和Objective-C的相关类型对应,不过他是值类型,而Objective-C的基础类型是引用类型,另外Swift还提供了几个集合类型,如Array, Set, 和 Dictionary;Swift引入一些Objective-C里面没有的元祖类型,这个在C#里倒是有类似的,也是这个名词。 Swift语言是一种类型安全的强类型语言,不是类似JavaScript的弱类型,能够在提供开发效率的同时,减少常规出错的可能,使我们在开发阶段尽量发现一些类型转换的错误并及时处理。
常量和变量复制代码
- let maximumNumberOfLoginAttempts = 10
- var currentLoginAttempt = 0
常量用let定义,变量用var定义,它们均可以通过自动推导类型,如上面的就是指定为整形的类型。
也可以通过逗号分开多个定义,如下所示
复制代码
- var x = 0.0, y = 0.0, z = 0.0
如果我们的变量没有初始化值来确定它的类型,我们可以通过指定类型来定义变量,如下所示
复制代码
- var welcomeMessage: String
- var red, green, blue: Double
变量的打印,可以在输出字符串中用括号包含变量输出,括号前加斜杠 \ 符号。
复制代码
- print(friendlyWelcome)
- // Prints "Bonjour!"
- print("The current value of friendlyWelcome is \(friendlyWelcome)")
- // Prints "The current value of friendlyWelcome is Bonjour!"
注释符
复制代码
- // This is a comment.
- /* This is also a comment
- but is 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. */
上面分别是常规的的注释,以及Swift支持嵌套的注释符号
分号
Swift语句的划分可以不用分号,不过你加分号也可以,如果加分号,则可以多条语句放在一行。
复制代码
- let cat = "??"; print(cat)
整型
复制代码
- 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类型,如Int32,Int64,我们一般采用int类型即可,这样可以在不同的系统平台有不同的意义。
在32位平台,Int代表是Int32
在64位平台,Int代表Int64
浮点数字
Swift的浮点数字类型包括有Float(单精度)和Double(双精度)两个类型,Float代表32位浮点数字,Double代表64位浮点数字。
默认通过小数值推导的变量或者常量的类型是Double,而非Float。
数字文字
复制代码
- let decimalInteger = 17
- let binaryInteger = 0b10001 // 17 二进制
- let octalInteger = 0o21 // 17 八进制
- let hexadecimalInteger = 0x11 // 17 十六进制
复制代码
- let decimalDouble = 12.1875
- let exponentDouble = 1.21875e1 //科学计数法 1.21875*10
- let hexadecimalDouble = 0xC.3p0 // p0代表 2的0次方
上面是科学计数方式的几种方式
复制代码
- let paddedDouble = 000123.456
- let oneMillion = 1_000_000
- let justOverOneMillion = 1_000_000.000_000_1
上面是使用0代替补齐签名数字,以及下划线来标识数字分割,方便阅读
复制代码
- let three = 3
- let pointOneFourOneFiveNine = 0.14159
- let pi = Double(three) + pointOneFourOneFiveNine
常量 three 初始化位整形类型, pointOneFourOneFiveNine 推导为Double类型,而pi则通过Double转换推导为Double类型,这样右边两个都是Double类型,可以进行相加的运算处理了。
布尔类型
复制代码
- let orangesAreOrange = true
- let turnipsAreDelicious = false
这个没有什么好讲的,就是语言默认有布尔类型提供,相对于Objective-C的非0则为True而言,布尔类型只有两个字,True或者False。
布尔类型可以用于条件判断等处理,如下
复制代码
- if turnipsAreDelicious {
- print("Mmm, tasty turnips!")
- } else {
- print("Eww, turnips are horrible.")
- }
元祖类型
元祖类型就是组合多个值的一个对象类型,在组合中的类型可以是任何Swift的类型,而且不必所有的值为相同类型。
复制代码
- let http404Error = (404, "Not Found")
- // http404Error is of type (Int, String), and equals (404, "Not Found")
另外可以解构对应的元祖类型的值到对应的常量或者变量里面,如下代码
复制代码
- let (statusCode, statusMessage) = http404Error
- print("The status code is \(statusCode)")
- // Prints "The status code is 404"
- print("The status message is \(statusMessage)")
- // Prints "The status message is Not Found"
也可以通过下划线来忽略相关的值,如下
复制代码
- let (justTheStatusCode, _) = http404Error
- print("The status code is \(justTheStatusCode)")
元祖对象里面的值可以通过数字索引来引用,如0,1的属性,如下
复制代码
- print("The status code is \(http404Error.0)")
- // Prints "The status code is 404"
- print("The status message is \(http404Error.1)")
- // Prints "The status message is Not Found"
可空类型
这个和C#里面的可空类型是对应的,也就是对象可能有值,也可能没有值
复制代码
- let possibleNumber = "123"
- let convertedNumber = Int(possibleNumber)
- // convertedNumber 推导类型为 "Int?", 或者 "optional Int"
Int类型的构造函数为可空构造函数,有可能转换失败,因此返回的为可空Int类型
可空类型可以通过设置nil,来设置它为无值状态
复制代码
- var serverResponseCode: Int? = 404
- // serverResponseCode contains an actual Int value of 404
- serverResponseCode = nil
- // serverResponseCode now contains no value
对于可空类型,如果确认它的值非空,那么可以强行解构它的值对象,访问它的值在变量后面增加一个!符号,如下所示
复制代码
- if convertedNumber != nil {
- print("convertedNumber has an integer value of \(convertedNumber!).")
- }
一般情况下,我们可以通过可空绑定的方式来处理这种对象的值,语句语法如下所示
复制代码
- if let constantName = someOptional {
- statements
- }
具体的语句如下所示
复制代码
- if let actualNumber = Int(possibleNumber) {
- print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
- } else {
- print("\"\(possibleNumber)\" could not be converted to an integer")
- }
- // Prints ""123" has an integer value of 123"
也可以多个let的可空绑定语句一起使用
复制代码
- if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
- print("\(firstNumber) < \(secondNumber) < 100")
- }
- // Prints "4 < 42 < 100"
- if let firstNumber = Int("4") {
- if let secondNumber = Int("42") {
- if firstNumber < secondNumber && secondNumber < 100 {
- print("\(firstNumber) < \(secondNumber) < 100")
- }
- }
- }
- // Prints "4 < 42 < 100"
解包可空类型可以通过!符号进行处理,一般情况如下所示进行判断
复制代码
- let possibleString: String? = "An optional string."
- let forcedString: String = possibleString! // requires an exclamation mark
- let assumedString: String! = "An implicitly unwrapped optional string."
- let implicitString: String = assumedString // no need for an exclamation mark
也可以使用可空绑定的let 语句进行隐式的解包,如下所示
复制代码
- if let definiteString = assumedString {
- print(definiteString)
- }
- // Prints "An implicitly unwrapped optional string."
错误处理
函数抛出异常,通过在函数里面使用throws进行声明,如下
复制代码
- func canThrowAnError() throws {
- // this function may or may not throw an error
- }
捕捉函数抛出的异常代码如下
复制代码
- do {
- try canThrowAnError()
- // no error was thrown
- } catch {
- // an error was thrown
- }
详细的案例代码如下所示
复制代码
- func makeASandwich() throws {
- // ...
- }
- do {
- try makeASandwich()
- eatASandwich()
- } catch SandwichError.outOfCleanDishes {
- washDishes()
- } catch SandwichError.missingIngredients(let ingredients) {
- buyGroceries(ingredients)
- }
断言调试
Swift提供一些标准库函数来进行断言调试,分为断言和预设条件的处理两部分。
断言调试仅仅在Debug调试模式运行,而预设条件则是调试模式和产品发布后都会运行的。
复制代码
- let age = -3
- assert(age >= 0, "A person's age can't be less than zero.")
- // This assertion fails because -3 is not >= 0.
复制代码
- if age > 10 {
- print("You can ride the roller-coaster or the ferris wheel.")
- } else if age > 0 {
- print("You can ride the ferris wheel.")
- } else {
- assertionFailure("A person's age can't be less than zero.")
- }
预设条件代码如下,用来对一些条件进行校验
复制代码
- // In the implementation of a subscript...
- precondition(index > 0, "Index must be greater than zero.")