【Swift】学习笔记(五)——控制语句(if,switch,for-in,for,while,do-while)

在代码业务中,条件判断是必不可少的,控制流程的语句在每种语言中都是差不多的。swift包括了:

if,switch,for-in,for,while,do-while

if 条件语句 (if else)    (if... else if ...  else)

判断条件为true时执行相关代码。例如:

var a = 0

if a > 0 {

println("a > 0")

}else if a == 0{

println("a = 0")

}else{

println("a < 0")

}

switch switch语句会尝试把某个值与若干个模式(pattern)进行匹配。根据第一个匹配成功的模式,switch语句会执行对应的代码

例如:

let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
    println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
    println("\(someCharacter) is a consonant")
default:
    println("\(someCharacter) is not a vowel or a consonant")
}

switch有几个注意事项:

1、case语句下必须包含至少一行代码

2、case语句下可以不包含break,它不存在隐式的贯穿

3、case可以进行区间匹配

let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount: String
switch count {
case 0:
    naturalCount = "no"
case 1...3:
    naturalCount = "a few"
case 4...9:
    naturalCount = "several"
case 10...99:
    naturalCount = "tens of"
case 100...999:
    naturalCount = "hundreds of"
case 1000...999_999:
    naturalCount = "thousands of"
default:
    naturalCount = "millions and millions of"
}
println("There are \(naturalCount) \(countedThings).")

4、元组   你可以使用元组在同一个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")
}

5、值绑定   case 分支的模式允许将匹配的值绑定到一个临时的常量或变量,这些常量或变量在该 case 分支里就可以被引用了——这种行为被称为值绑定

例如:

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    println("on the x-axis with an x value of \(x)")
case (0, let y):
    println("on the y-axis with a y value of \(y)")
case let (x, y):
    println("somewhere else at (\(x), \(y))")
}
// 输出 "on the x-axis with an x value of 2"

6、where条件判断

例如

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")
}
// 输出 "(1, -1) is on the line x == -y"

7、能够使用return,continue,break,fallthrough 来改变所有控制语句的控制流程。这叫做控制转移。

a)continue语句告诉一个循环体立刻停止本次循环迭代,重新开始下次循环迭代。就好像在说“本次循环迭代我已经执行完了”,但是并不会离开整个循环体。

b)break语句会立刻结束整个控制流的执行。当你想要更早的结束一个switch代码块或者一个循环体时,你都可以使用break语句,if for  for-in  while  do-while 这些都能够用break跳出控制,

c)fallthrough 贯穿   这个和第二点一样。

d)return语句会立刻终止当前代码的执行,并返回。用在方法控制中比较多。

8、给while取一个名字  例如

mainLabel: while a > 0{
	if a ==100 {
		break mainLabel
	}
}

for 循环  for-in循环

for循环用来按照指定的次数多次执行一系列语句。Swift 提供两种for循环形式:

a)for-in用来遍历一个区间(range),序列(sequence),集合(collection),系列(progression)里面所有的元素执行一系列语句。

b)for条件递增(for-condition-increment)语句,用来重复执行一系列语句直到达成特定条件达成,一般通过在每次循环完成后增加计数器的值来实现。

遍历区间:

for index in 1...5 {
    println("\(index) times 5 is \(index * 5)")
}

遍历数组:

let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
    println("Hello, \(name)!")
}

遍历字典集合:

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

还可以遍历字符:

for character in "Hello" {
    println(character)
}

增量循环:

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

while循环  do-while循环

while循环,每次在循环开始时计算条件是否符合;

do-while循环,每次在循环结束时计算条件是否符合。

while循环:

while condition {
statements
}
while a > 0{
	println("a value \(a)");
}

do-while循环

do {
statements
} while condition
do{
	println("a value \(a)")
}while a > 0

哇、好强大,这循环用起来应该很爽啊。。。虽然用得最多的就是for循环,呵呵。

时间: 2024-07-31 15:26:18

【Swift】学习笔记(五)——控制语句(if,switch,for-in,for,while,do-while)的相关文章

Swift学习笔记五:循环和条件语句

一.循环语句 1. for循环 1) for -in 循环,对于数据范围,序列,集合等中的每一个元素,都执行一次 for a in 0...5{}    //循环迭代,从a=0到a=5,执行{}里的代码 注意:a只循环中存在,也就是出了{}a就不存在了 或者遍历数组 let a = [1,2,3] for b in a{} //循环迭代,从b=1到b=3 如果你不需要序列中的每一个值,可以使用_来忽略它,仅仅只是使用循环体本身: for _ in 0...5{}    //循环执行{}里的代码,

swift学习笔记(五)构造过程

构造过程是为了使用某个类.结构体或枚举类型的实例而进行的准备过程.在构造过程中,对每一个属性进行了初始值预设和其它必要的准备和初始化工作. 与OC相比,swift的构造函数.不须要返回值.同一时候,在类和结构体的构造过程中,必须对全部的存储类型属性,包括继承自父类的属性.赋予合适的初始值.存储类型值不能处于一个未知状态. 在对属性进行初始化过程中,有两种方法,第一:使用构造方法,第二:在定义属性时,直接赋予默认值. 当使用构造方法对属性赋值时,不会触发不论什么的属性观測器. 当一个属性总是使用同

Swift学习笔记五

基础运算符 Swift的大部分运算符和C及OC相同,也分一元二元多元的,这里只记录一些Swift特有的性质或写法. 赋值运算符( = ) 在等号右边是一个有多个值的元组时,它的成员值可以分解并同时分别赋值给常量或者变量: let (x, y) = (1, 2) // x is equal to 1, and y is equal to 2 和C.OC不同的是,赋值运算符本身并不返回值,因此如下写法是错误的: if x = y { // this is not valid, because x =

Swift 学习笔记十五:扩展

扩展就是向一个已有的类.结构体或枚举类型添加新功能(functionality).扩展和 Objective-C 中的分类(categories)类似.(不过与Objective-C不同的是,Swift 的扩展没有名字.) Swift 中的扩展可以: 1.添加计算型属性和计算静态属性 2.定义实例方法和类型方法 3.提供新的构造器 4.定义下标 5.定义和使用新的嵌套类型 6.使一个已有类型符合某个协议 一.扩展属性,构造器,方法 class Human{ var name:String? va

SWIFT学习笔记05

1.Swift 无需写break,所以不会发生这种贯穿(fallthrough)的情况.2.//用不到变量名,可用"_"替换 for _ in 1...power { answer *= base } 3.case 可以匹配更多的类型模式,包括区间匹配(range matching),元组(tuple)和特定类型的描述. 可以这样用case case 1...3: naturalCount = "a few" 4.如果存在多个匹配,那么只会执行第一个被匹配到的 ca

Swift学习笔记(二)参数类型

关于参数类型,在以前的编程过程中,很多时间都忽视了形参与实参的区别.通过这两天的学习,算是捡回了漏掉的知识. 在swift中,参数有形参和实参之分,形参即只能在函数内部调用的参数,默认是不能修改的,如果想要修改就需要在参数前添加var声明. 但这样的声明过后,仍旧不会改变实参的值,这样就要用到inout了,传递给inout的参数类型必须是var类型的,不能是let类型或者字面类型,(字面类型是在swift中常提的一个术语,个人认为就是赋值语句,也不能修改)而且在传递过程中,要用传值符号"&

Swift学习笔记

Apple 新推的Swift已经好几天了.对于向我这样的oc都还没完全琢磨透彻的菜鸟来说--(简直就是福利啊,joke) 看了几天的Swift,只是有了基本的印象.总感觉比较换混乱,可能源自与自己没怎么学过脚本语言.索性,边看边记,加深印象. 本来部分内容源自Apple的<The Swift Programming Language>以及互联网教程.其余内容均为个人理解,不保证正确. 进入正题: 1.Swift是什么? Apple唤他作:雨燕.其实英语过了四级的都应该看出来,Swift还有一层

Swift学习笔记(一):基础

一.常量 & 变量 //常量 let constantsTeam = 1 //变量 var variablesTeam = 2 尽可能使用常量,这样更清晰并且内存更不容易肾亏. 二.显示/隐式指定类型 //隐式 let inferredTeam = 3 //显式 let explicitTeam:Int = 4 三.字符串输出 //通过\(变量或常量名)来引用组合字符串 println("\(inferredTeam) is bigger than \(variablesTeam)!&q

Swift学习笔记:类和结构

一.类和结构的异同 类和结构有一些相似的地方,它们都可以: 1. 定义一些可以赋值的属性: 2. 定义具有功能性的方法 3. 定义下标,使用下标语法 4. 定义初始化方法来设置初始状态 5. 在原实现方法上的可扩展性 根据协议提供某一特定类别的基本功能 1. 类还有一些结构不具备的特性: 2. 类的继承性 3. 对类实例实时的类型转换 4. 析构一个类的实例使之释放空间 5. 引用计数,一个类实例可以有多个引用 1. 定义语法 struct Name{ let firstName = "&quo