Swift编程高级教程
常量与变量
常量和变量是某个特定类型的值的名字,如果在程序运行时值不能被修改的是一个常量,反之是一个变量。 常量和变量的声明Swift中的常量和变量在使用前必须先声明。其中let关键字声明常量,var关键字声明变量: //声明一个名为maximumNumberOfLoginAttempts的整型常量,并且值为10 let maximumNumberOfLoginAttempts = 10 //声明一个名为currentLoginAttempt的整型变量,并且值为0 var currentLoginAttempt = 0 可以在同一行声明多个变量,中间用逗号,隔开: var x = 0.0,y = 0.0,z = 0.0
变量的值可以进行修改: var friendlyWelcome = "Hello!" friendlyWelcome = "Bonjour!" //friendlyWelcome的值发生改变 常量的值一旦设置后就不能在修改: let languageName = "Swift" languageName = "Swift++" //编译时出错 类型说明在Swift中声明常量或者变量可以在后面用冒号:指定它们的数据类型。 //声明一个String类型的变量,可以存放String类型的值 var welcomeMessage: String
命名规则Swift中可以使用任意字符给常量和变量命名,包括Unicode编码,比如中文、Emoji等: let π = 3.14159 let 你好 = "你好世界" let dog = "dogcow" 名字里面不能包含数学运算符、箭头、非法的Unicode字符以及不能识别的字符等,并且不能以数字开头。同一个作用域的变量或者常量不能同名。
打印变量的值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”
属性观察者属性观察者用来观察和响应属性值的变化。每次设置属性的值都会调用相应的观察者,哪怕是设置相同的值。 可以给除延时存储属性以外的任何存储属性添加观察者。通过重写属性,可以在子类中给父类的属性(包括存储属性和计算属性)添加观察者。
通过下面两个方法对属性进行观察:
如果没有给willSet指定参数的话,编译器默认提供一个newValue做为参数。同样,在didSet中如果没有提供参数的话,默认为oldValue。
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。 var shoppingList: String[] = ["Eggs","Milk"] // 把shoppingList初始化为两个初始数据元素 这个shoppingList变量通过String[]形式被声明为一个String类型值的数组,因为这个特定的数组被指定了值类型String,所以我们只能用这个数组类存储String值,这里我们存储了两个字面常量String值(“Eggs”和“Milk”)。
这里,这个字面常量数组只包含了2个String值,他能匹配shoppingList数组的类型声明,所以可以用他来给shoppingList变量赋值初始化。 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的名字,从而忽略这个常量的值: 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循环可以用下面的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"
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"
流程控制-跳转语句流程转换语句(跳转语句)可以改变代码的执行流程。Swift包含下面四种跳转语句:
下面会对continue、break和fallthrough进行讲解,而return表达式将在函数中进行介绍。 continue表达式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."
标号语句 在循环或者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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |