您的位置:首页 > 移动开发 > Swift

Swift编程高级教程

2014-06-07 13:24 357 查看
整合了一下别人的博客方便大家阅读,全篇转载,纯属喜好swift。

From:http://blog.diveinedu.net/

常量与变量

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

常量和变量的声明

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 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
则终止当前这次循环的执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: