Swift编程高级教程

常量与变量

 

常量和变量是某个特定类型的值的名字,若是在程序运行时值不能被修改的是一个常量,反之是一个变量。 数组

常量和变量的声明

Swift中的常量和变量在使用前必须先声明。其中let关键字声明常量,var关键字声明变量: app

//声明一个名为maximumNumberOfLoginAttempts的整型常量,而且值为10 let maximumNumberOfLoginAttempts = 10 //声明一个名为currentLoginAttempt的整型变量,而且值为0 var currentLoginAttempt = 0

能够在同一行声明多个变量,中间用逗号,隔开: ide

var x = 0.0, y = 0.0, z = 0.0

提示
若是在程序运行的时候值不须要发生改变,应该将它们声明为常量,不然声明为变量 函数

变量的值能够进行修改: oop

var friendlyWelcome = "Hello!" friendlyWelcome = "Bonjour!" //friendlyWelcome的值发生改变

常量的值一旦设置后就不能在修改: this

let languageName = "Swift" languageName = "Swift++" //编译时出错

类型说明

在Swift中声明常量或者变量能够在后面用冒号:指定它们的数据类型。 编码

//声明一个String类型的变量,能够存放String类型的值 var welcomeMessage: String

提示
实际应用中不多须要指定变量数据类型,Swift会根据所设置的值的类型进行推导。 spa

命名规则

Swift中可使用任意字符给常量和变量命名,包括Unicode编码,好比中文、Emoji等: .net

let π = 3.14159 let 你好 = "你好世界" let dog = "dogcow"

名字里面不能包含数学运算符、箭头、非法的Unicode字符以及不能识别的字符等,而且不能以数字开头。同一个做用域的变量或者常量不能同名。 code

提示
若是想用关键字做为变量的名字,要用(`)包裹起来。为了方便理解,若是不是万不得已,不该该使用关键字做为变量的名字。

打印变量的值

println函数能够打印常量或者变量的值:

println("The current value of friendlyWelcome is \(friendlyWelcome)") //打印“The current value of friendlyWelcome is Bonjour!”

注释

注释是用来帮助理解和记忆代码功能的,并不会参与编译。Swift有两种注释形式,单行注释和多行注释:

//这是单行注释,用两个斜线开头,直到改行的结尾 /*这是多行注释, 能够横跨不少行, /*比C语言更加NB的是,*/ 它居然还支持嵌套的注释!*/

分号

Swift中语句结尾的分号;不是必须的,不过若是想要在同一行中写多个语句,则须要使用;进行分隔。


简化setter的声明

若是没有为计算属性的setter的新值指定名字,则默认使用newValue。下面是Rect结构体的另一种写法:

struct Cuboid { var width = 0.0, height = 0.0, depth = 0.0 var volume: Double { return width * height * depth } } let fourByFiveByTwo = Cuboid(width: 4.0, height: 5.0, depth: 2.0) println("the volume of fourByFiveByTwo is \(fourByFiveByTwo.volume)") //打印“the volume of fourByFiveByTwo is 40.0” 

属性观察者

属性观察者用来观察和响应属性值的变化。每次设置属性的值都会调用相应的观察者,哪怕是设置相同的值。

能够给除延时存储属性之外的任何存储属性添加观察者。经过重写属性,能够在子类中给父类的属性(包括存储属性和计算属性)添加观察者。

提示
不须要给类自己定义的计算属性添加观察者,彻底能够在计算属性的setter中完成对值的观察。

经过下面两个方法对属性进行观察:

  • willSet在属性的值发生改变以前调用。
  • didSet在设置完属性的值后调用。

若是没有给willSet指定参数的话,编译器默认提供一个newValue作为参数。一样,在didSet中若是没有提供参数的话,默认为oldValue。

提示
willSet和didSet观察者在属性进行初始化的时候不会被调用。

struct SomeStructure { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { //return an Int value here } } enum SomeEnumeration { static var storedTypeProperty = "Some value." static var computedTypeProperty: Int { //return an Int value here } } class SomeClass { class var computedTypeProperty: Int { //return an Int value here } } 

提示
上面的计算属性都是只读的,但实际上能够定义为可读可写

使用类型属性

类型属性经过类型名字和点操做符进行访问和设置,而不是经过实例对象:

println(SomeClass.computedTypeProperty) //print "42" println(SomeStructure.storedTypeProperty) //prints "Some value" SomeStructure.storedTypeProperty = "Another value." println(SomeStructure.storedTypeProperty) //prints "Another value." 

下面演示了如何使用一个结构体来对声道音量进行建模,其中每一个声道音量范围为0-10。
staticPropertiesVUMeter_2x

var shoppingList: String[] = ["Eggs", "Milk"] // 把shoppingList初始化为两个初始数据元素

这个shoppingList变量经过String[]形式被声明为一个String类型值的数组,由于这个特定的数组被指定了值类型String,因此咱们只能用这个数组类存储String值,这里咱们存储了两个字面常量String值(“Eggs”和“Milk”)。

提示
这个shoppingList是声明为变量(var说明符)而不是声明为常量(let说明符),由于后面的例子里将有更多的元素被加入这个数组.

这里,这个字面常量数组只包含了2个String值,他能匹配shoppingList数组的类型声明,因此能够用他来给shoppingList变量赋值初始化。
得益于Swift的类型推断机制,咱们在用数组字面常量来初始化一个数组时不须要明确指定他的类型,用以下这个很方便的方式:

println("Tht shopping list contains \(shoppingList.count) items.") // prints "The shopping list contains 2 items."

数组有一个叫作isEmpty的属性来表示该数组是否为空,即count属性等于 0:

shoppingList += "Baking Powder" //shoppingList now contains 4 items

咱们还有能够直接给一个数组加上另外一个类型一致的数组:

shoppingList.insert("Maple Syrup", atIndex: 0) // shoppingList now contains 7 items // "Maple Syrup" is now the first item in the list

当咱们须要在数组的某个地方移除一个既有元素的时候,能够调用数组的方法removeAtIndex,该方法的返回值是被移除掉的元素;

let mapleSyrup = shoppingList.removeAtIndex(0) // the item that was at index 0 has just been removed // shoppingList now contains 6 items, and no Maple Syrup // the mapleSyrup constant is now equal to the removed "Maple Syrup" string

当特殊状况咱们须要移除数组的最后一个元素的时候,咱们应该避免使用removeAtIndex方法,而直接使用简便方法removeLast来直接移除数组的最后一个元素,removeLast方法也是返回被移除的元素。

let apples = shoppingList.removeLast() // the last item in the array has just been removed // shoppingList now contains 5 items, and no cheese // the apples constant is now equal to the removed "Apples" string

数组元素的遍历

在Swift语言里,咱们能够用快速枚举(for-in)的方式来遍历整个数组的元素:

for (index, value) in enumerate(shoppingList) { println("Item \(index + 1): \(value)")
} // Item 1: Six eggs // Item 2: Milk // Item 3: Flour // Item 4: Baking Powder // Item 5: Bananas

数组建立与初始化

咱们能够用以下的语法来初始化一个肯定类型的空的数组(没有设置任何初始值):

var someInts = Int[]() println("someInts is of type Int[] with \(someInts.count) items.") // prints "someInts is of type Int[] with 0 items.

变量someInts的类型会被推断为Int[],由于他被赋值为一个Int[]类型的初始化方法的结果。
若是程序的上下文已经提供了其类型信息,好比一个函数的参数,已经申明了类型的变量或者常量,这样你能够用一个空数组的字面常量去给其赋值一个空的数组(这样写[]):

someInts.append(3) // someInts now contains 1 value of type Int someInts = [] // someInts is now an empty array, but is still of type Int[]

Swift的数组一样也提供了一个建立指定大小并指定元素默认值的初始化方法,咱们只需给初始化方法的参数传递元素个数(count)以及对应默认类型值(repeatedValue):

var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5) // anotherThreeDoubles is inferred as Double[], and equals [2.5, 2.5, 2.5]

最后,咱们数组也能够像字符串那样,能够把两个已有的类型一致的数组相加获得一个新的数组,新数组的类型由两个相加的数组的类型推断而来:

for index in 1...5 { println("\(index) times 5 is \(index * 5)")
} // 1 times 5 is 5 // 2 times 5 is 10 // 3 times 5 is 15 // 4 times 5 is 20 // 5 times 5 is 25

提示
index常量的做用域只在循环体里面。若是须要在外面使用它的值,则应该在循环体外面定义一个遍历。

若是不须要从范围中获取值的话,可使用下划线_代替常量index的名字,从而忽略这个常量的值:

let base = 3 let power = 10 var answer = 1 for _ in 1...power {
    answer *= base
} println("\(base) to the power of \(power) is \(answer)") //prints "3 to the power of 10 is 59049"

下面是使用for-in遍历数组里的元素:

let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4] for (animalName, legCount) in numberOfLegs { println("\(animalName)s have \(legCount) legs")
} //spiders have 8 legs //ants have 6 legs //cats have 4 legs

因为字典是无序的,所以迭代的顺序不必定和插入顺序相同。

对于字符串String进行遍历的时候,获得的是里面的字符Character:

for var index = 0; index < 3; ++index { println("index is \(index)")
} //index is 0 //index is 1 //index is 2

下面是这种循环的通用格式,for循环中的分号不能省略:
for 初始化; 循环条件; 递增变量 {
循环体语句
}
这些语句的执行顺序以下:

  1. 第一次进入是先执行初始化表达式,给循环中用到的常量和变量赋值。
  2. 执行循环条件表达式,若是为false,循环结束,不然执行花括号{}里的循环体语句。
  3. 循环体执行完后,递增遍历表达式执行,而后再回到上面的第2条。

这中形式的for循环能够用下面的while循环等价替换:

初始化
while 循环条件 {
    循环体语句
    递增变量
}

在初始化是声明的常量或变量的做用域为for循环里面,若是须要在循环结束后使用index的值,须要在for循环以前进行声明:

while 循环条件 {
    循环体语句
}

 

do-while循环

 

do-while循环的通用格式:

 

temperatureInFahrenheit = 40 if temperatureInFahrenheit <= 32 { println("It's very cold. Consider wearing a scarf.")
} else { println("It's not that cold. Wear a t-shirt.")
} //prints "It's not that cold. Wear a t-shirt."

若是须要增长更多的判断条件,能够将多个if-else语句连接起来:

temperatureInFahrenheit = 72 if temperatureInFahrenheit <= 32 { println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 { println("It's really warm. Don't forget to wear sunscreen.")
}

switch语句

switch语句能够将同一个值与多个判断条件进行比较,找出合适的代码进行执行。最简单的形式是将一个值与多个同类型的值进行比较:

let somePoint = (1, 1) switch somePoint { case (0, 0): println("(0, 0) is at the origin") case (_, 0): println("(\(somePoint.0), 0) is on the x-axis") case (0, _): println("(0, \(somePoint.1)) is on the y-axis") case (-2...2, -2...2): println("(\(somePoint.0), \(somePoint.1)) is inside the box") default: println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
} // prints "(1, 1) is inside the box"

coordinateGraphSimple_2x

Swift中case表示的范围能够是重叠的,可是会匹配最早发现的值。

值的绑定

switch可以将值绑定到临时的常量或变量上,而后在case中使用,被称为value binding。

let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: println("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: println("(\(x), \(y)) is on the line x == -y") case let (x, y): println("(\(x), \(y)) is just some arbitrary point")
} // prints "(1, -1) is on the line x == -y"

coordinateGraphComplex_2x


流程控制-跳转语句

流程转换语句(跳转语句)能够改变代码的执行流程。Swift包含下面四种跳转语句:

  • continue
  • break
  • fallthrough
  • return

下面会对continue、break和fallthrough进行讲解,而return表达式将在函数中进行介绍。

continue表达式

continue语句能够提早结束一次循环,之间调到第二次循环开始,可是并不会终止循环。

提示
在for-condition-increment类型的循环中,自增语句在continue后仍然会执行。

下面的例子会删除字符串中的元音字符和空格:

let numberSymbol: Character = "三" // Simplified Chinese for the number 3 var possibleIntegerValue: Int? switch numberSymbol { case "1", "١", "一", "๑":
    possibleIntegerValue = 1 case "2", "٢", "二", "๒":
    possibleIntegerValue = 2 case "3", "٣", "三", "๓":
    possibleIntegerValue = 3 case "4", "٤", "四", "๔":
    possibleIntegerValue = 4 default: break } if let integerValue = possibleIntegerValue { println("The integer value of \(numberSymbol) is \(integerValue).")
} else { println("An integer value could not be found for \(numberSymbol).")
} // prints "The integer value of 三 is 3."

fallthrough语句

Swift的switch语句中不能在一个case执行完后继续执行另一个case,这遇C语言中的状况不同。若是你须要实现相似于C语言中switch的行为,可使用fallthrough关键字。

let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also" fallthrough default:
    description += " an integer." } println(description) // prints "The number 5 is a prime number, and also an integer."

提示
fallthrough语句执行后,switch不会再去检查下面的case的值。

标号语句

在循环或者switch语句中使用break只能跳出最内层,若是有多个循环语句嵌套的话,须要使用标号语句才能一次性跳出这些循环。
标号语句的基本写法为:

<code class="go hljs" style="font-weight: bold; color: #6e6b5e;" data-origin="" <pre><code="" while="" 条件语句="" {"="">标号名称: while 条件语句 {
    循环体
}

下面是标号语句的一个例子:

let finalSquare = 25 var board = Int[](count: finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02 board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08 var square = 0 var diceRoll = 0 gameLoop: while square != finalSquare { if ++diceRoll == 7 { diceRoll = 1 } switch square + diceRoll { case finalSquare: // diceRoll will move us to the final square, so the game is over break gameLoop case let newSquare where newSquare > finalSquare: // diceRoll will move us beyond the final square, so roll again continue gameLoop default: // this is a valid move, so find out its effect square += diceRoll
        square += board[square]
    }
} println("Game over!")

break或continue执行后,会跳转到标号语句处执行,其中break会终止循环,而continue则终止当前此次循环的执行。


blog.diveinedu.net