经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 移动开发 » Swift » 查看文章
快看Sample代码,速学Swift语言(2)-基础介绍
来源:cnblogs  作者:伍华聪  时间:2018/9/25 20:29:49  对本文有异议

Swift语言是一个新的编程语言,用于iOS, macOS, watchOS, 和 tvOS的开发,不过Swift很多部分内容,我们可以从C或者Objective-C的开发经验获得一种熟悉感。Swift提供很多基础类型,如Int,String,Double,Bool等类型,它和Objective-C的相关类型对应,不过他是值类型,而Objective-C的基础类型是引用类型,另外Swift还提供了几个集合类型,如ArraySet, 和 Dictionary;Swift引入一些Objective-C里面没有的元祖类型,这个在C#里倒是有类似的,也是这个名词。 Swift语言是一种类型安全的强类型语言,不是类似JavaScript的弱类型,能够在提供开发效率的同时,减少常规出错的可能,使我们在开发阶段尽量发现一些类型转换的错误并及时处理。

常量和变量

  1. let maximumNumberOfLoginAttempts = 10
  2. var currentLoginAttempt = 0

 常量用let定义,变量用var定义,它们均可以通过自动推导类型,如上面的就是指定为整形的类型。

也可以通过逗号分开多个定义,如下所示

  1. var x = 0.0, y = 0.0, z = 0.0

 如果我们的变量没有初始化值来确定它的类型,我们可以通过指定类型来定义变量,如下所示

  1. var welcomeMessage: String
  2.  
  3. var red, green, blue: Double

 变量的打印,可以在输出字符串中用括号包含变量输出,括号前加斜杠 \ 符号。

  1. print(friendlyWelcome)
  2. // Prints "Bonjour!"
  3. print("The current value of friendlyWelcome is \(friendlyWelcome)")
  4. // Prints "The current value of friendlyWelcome is Bonjour!"

 

注释符

  1. // This is a comment.
  2.  
  3. /* This is also a comment
  4. but is written over multiple lines. */
  5.  
  6. /* This is the start of the first multiline comment.
  7. /* This is the second, nested multiline comment. */
  8. This is the end of the first multiline comment. */

 上面分别是常规的的注释,以及Swift支持嵌套的注释符号

 

分号

Swift语句的划分可以不用分号,不过你加分号也可以,如果加分号,则可以多条语句放在一行。

  1. let cat = "??"; print(cat)

 

整型

  1. let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
  2. 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。

 

数字文字

  1. let decimalInteger = 17
  2. let binaryInteger = 0b10001 // 17 二进制
  3. let octalInteger = 0o21 // 17 八进制
  4. let hexadecimalInteger = 0x11 // 17 十六进制

 

  1. let decimalDouble = 12.1875
  2. let exponentDouble = 1.21875e1 //科学计数法 1.21875*10
  3. let hexadecimalDouble = 0xC.3p0 // p0代表 2的0次方

 上面是科学计数方式的几种方式

 

  1. let paddedDouble = 000123.456
  2. let oneMillion = 1_000_000
  3. let justOverOneMillion = 1_000_000.000_000_1

 上面是使用0代替补齐签名数字,以及下划线来标识数字分割,方便阅读

 

  1. let three = 3
  2. let pointOneFourOneFiveNine = 0.14159
  3. let pi = Double(three) + pointOneFourOneFiveNine

 常量 three 初始化位整形类型, pointOneFourOneFiveNine 推导为Double类型,而pi则通过Double转换推导为Double类型,这样右边两个都是Double类型,可以进行相加的运算处理了。

 

布尔类型

  1. let orangesAreOrange = true
  2. let turnipsAreDelicious = false

 这个没有什么好讲的,就是语言默认有布尔类型提供,相对于Objective-C的非0则为True而言,布尔类型只有两个字,True或者False。

布尔类型可以用于条件判断等处理,如下

  1. if turnipsAreDelicious {
  2. print("Mmm, tasty turnips!")
  3. } else {
  4. print("Eww, turnips are horrible.")
  5. }

 

元祖类型

元祖类型就是组合多个值的一个对象类型,在组合中的类型可以是任何Swift的类型,而且不必所有的值为相同类型。

  1. let http404Error = (404, "Not Found")
  2. // http404Error is of type (Int, String), and equals (404, "Not Found")

 另外可以解构对应的元祖类型的值到对应的常量或者变量里面,如下代码

  1. let (statusCode, statusMessage) = http404Error
  2. print("The status code is \(statusCode)")
  3. // Prints "The status code is 404"
  4. print("The status message is \(statusMessage)")
  5. // Prints "The status message is Not Found"

 也可以通过下划线来忽略相关的值,如下

  1. let (justTheStatusCode, _) = http404Error
  2. print("The status code is \(justTheStatusCode)")

 元祖对象里面的值可以通过数字索引来引用,如0,1的属性,如下

  1. print("The status code is \(http404Error.0)")
  2. // Prints "The status code is 404"
  3. print("The status message is \(http404Error.1)")
  4. // Prints "The status message is Not Found"

 

可空类型

这个和C#里面的可空类型是对应的,也就是对象可能有值,也可能没有值

  1. let possibleNumber = "123"
  2. let convertedNumber = Int(possibleNumber)
  3. // convertedNumber 推导类型为 "Int?", 或者 "optional Int"

Int类型的构造函数为可空构造函数,有可能转换失败,因此返回的为可空Int类型

可空类型可以通过设置nil,来设置它为无值状态

  1. var serverResponseCode: Int? = 404
  2. // serverResponseCode contains an actual Int value of 404
  3. serverResponseCode = nil
  4. // serverResponseCode now contains no value

 对于可空类型,如果确认它的值非空,那么可以强行解构它的值对象,访问它的值在变量后面增加一个!符号,如下所示

  1. if convertedNumber != nil {
  2. print("convertedNumber has an integer value of \(convertedNumber!).")
  3. }

 一般情况下,我们可以通过可空绑定的方式来处理这种对象的值,语句语法如下所示

  1. if let constantName = someOptional {
  2. statements
  3. }

 具体的语句如下所示

  1. if let actualNumber = Int(possibleNumber) {
  2. print("\"\(possibleNumber)\" has an integer value of \(actualNumber)")
  3. } else {
  4. print("\"\(possibleNumber)\" could not be converted to an integer")
  5. }
  6. // Prints ""123" has an integer value of 123"

 也可以多个let的可空绑定语句一起使用

  1. if let firstNumber = Int("4"), let secondNumber = Int("42"), firstNumber < secondNumber && secondNumber < 100 {
  2. print("\(firstNumber) < \(secondNumber) < 100")
  3. }
  4. // Prints "4 < 42 < 100"
  5. if let firstNumber = Int("4") {
  6. if let secondNumber = Int("42") {
  7. if firstNumber < secondNumber && secondNumber < 100 {
  8. print("\(firstNumber) < \(secondNumber) < 100")
  9. }
  10. }
  11. }
  12. // Prints "4 < 42 < 100"

 

解包可空类型可以通过!符号进行处理,一般情况如下所示进行判断

  1. let possibleString: String? = "An optional string."
  2. let forcedString: String = possibleString! // requires an exclamation mark
  3. let assumedString: String! = "An implicitly unwrapped optional string."
  4. let implicitString: String = assumedString // no need for an exclamation mark

 也可以使用可空绑定的let 语句进行隐式的解包,如下所示

  1. if let definiteString = assumedString {
  2. print(definiteString)
  3. }
  4. // Prints "An implicitly unwrapped optional string."

 

错误处理

函数抛出异常,通过在函数里面使用throws进行声明,如下

  1. func canThrowAnError() throws {
  2. // this function may or may not throw an error
  3. }

 捕捉函数抛出的异常代码如下

  1. do {
  2. try canThrowAnError()
  3. // no error was thrown
  4. } catch {
  5. // an error was thrown
  6. }

 详细的案例代码如下所示

  1. func makeASandwich() throws {
  2. // ...
  3. }
  4. do {
  5. try makeASandwich()
  6. eatASandwich()
  7. } catch SandwichError.outOfCleanDishes {
  8. washDishes()
  9. } catch SandwichError.missingIngredients(let ingredients) {
  10. buyGroceries(ingredients)
  11. }

 

断言调试

Swift提供一些标准库函数来进行断言调试,分为断言和预设条件的处理两部分。

断言调试仅仅在Debug调试模式运行,而预设条件则是调试模式和产品发布后都会运行的。

  1. let age = -3
  2. assert(age >= 0, "A person's age can't be less than zero.")
  3. // This assertion fails because -3 is not >= 0.

 

  1. if age > 10 {
  2. print("You can ride the roller-coaster or the ferris wheel.")
  3. } else if age > 0 {
  4. print("You can ride the ferris wheel.")
  5. } else {
  6. assertionFailure("A person's age can't be less than zero.")
  7. }

 预设条件代码如下,用来对一些条件进行校验

  1. // In the implementation of a subscript...
  2. precondition(index > 0, "Index must be greater than zero.")

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号