Swift编程高级教程

Swift编程高级教程,第1张

概述常量与变量   常量和变量是某个特定类型的值的名字,如果在程序运行时值不能被修改的是一个常量,反之是一个变量。 常量和变量的声明 Swift中的常量和变量在使用前必须先声明。其中let关键字声明常量,var关键字声明变量: //声明一个名为maximumNumberOfLoginAttempts的整型常量,并且值为10 let maximumNumberOfLoginAttempts = 10 / 常量与变量

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

常量和变量的声明

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会根据所设置的值的类型进行推导。

命名规则

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” 
属性观察者

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

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

提示
不需要给类本身定义的计算属性添加观察者,完全可以在计算属性的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。

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初始化;循环条件;递增变量{
循环体语句
}
这些语句的执行顺序如下:

第一次进入是先执行初始化表达式,给循环中用到的常量和变量赋值。 执行循环条件表达式,如果为false,循环结束,否则执行花括号{}里的循环体语句。 循环体执行完后,递增遍历表达式执行,然后再回到上面的第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"

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、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   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

总结

以上是内存溢出为你收集整理的Swift编程高级教程全部内容,希望文章能够帮你解决Swift编程高级教程所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1080949.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存