一些swift基础知识点

Mark ,防忘

  1. 扩展可以向一个类型添加新的方法,但是不能重写已有的方法
  2. 元组:可获取性,可省略性,可索引性,可命名性
  3. 如何使用元组(1)

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”

  1. 你可以在定义元组的时候给其中的单个元素命名:

let http200Status = (statusCode: 200, description: “OK”)
//在命名之后,你就可以通过访问名字来获取元素的值了:
print(“The status code is (http200Status.statusCode)”)
// prints “The status code is 200”
print(“The status message is (http200Status.description)”)
// prints “The status message is OK”

  1. if let 语句只有在赋值量不为nil时才会赋给被赋值量
  2. 使用 if 语句创建的常量和变量只在if语句的函数体内有效。
  3. 在 guard 语句中创建的常量和变量在 guard 语句后的代码中也可用。相反,在 guard 语句中创建的常量和变量在 guard 语句后的代码中也可用。
  4. 一段有意思的代码

var string :String = “hello,world”
func printAndCount(string: String) -> Int {
print(string)
return string.count
}
func printWithoutCounting(string: String) {
let _ = printAndCount(string: string)
} //在这里,上面一个函数被调用,因此它会打印出信息

  1. 为了让函数返回多个值作为一个复合的返回值,你可以使用元组类型作为返回类型。
  2. 输入输出函数举例

func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
//使用函数
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print(“someInt is now \(someInt), and anotherInt is now \(anotherInt)”)
// prints “someInt is now 107, and anotherInt is now 3”

猜你喜欢

转载自blog.csdn.net/soviet1941/article/details/86175579