swift笔记(3)

来源:互联网 发布:网龙网络控股有限公司 编辑:程序博客网 时间:2024/05/20 10:23

范围匹配

switch语句的case中可以匹配一个数值范围,比如:

123456789101112131415161718192021
let count = 3_000_000_000_000let countedThings = "stars in the Milky Way"var naturalCount: Stringswitch 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).")// prints "There are millions and millions of stars in the Milky Way."

元组

case中还可以直接测试元组是否符合相应的条件,_可以匹配任意值。

下面的例子是判断(x,y)是否在矩形中,元组类型是(Int,Int)

1234567891011121314
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"

数值绑定

在case匹配的同时,可以将switch语句中的值绑定给一个特定的常量或者变量,以便在case的语句中使用。比如:

12345678910
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))")}// prints "on the x-axis with an x value of 2"

Where关键词

switch语句可以使用where关键词来增加判断的条件,在下面的例子中:

12345678910
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"

fallthrough

由于Swift中的switch语句不会自动的因为没有break而跳转到下一个case,因此如果需要想C语言中那样,依次执行每个case的时候,就需要用到fallthrough关键词。

像下面这个例子一样,default分支最终都会被执行:

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

标签语句

switch和循环可以互相嵌套,循环之间也可以互相嵌套,因此在使用break或者continue的时候,需要知道到底是对哪个语句起作用。这就需要用到标签语句。标签语句的一般形式如下:

123
label name: while condition {statements}


闭包(Closures)是独立的函数代码块,能在代码中传递及使用。Swift中的闭包与C和Objective-C中的代码块及其它编程语言中的匿名函数相似。
枚举成员可以指定任何类型,每个成员都可以存储的不同的相关值,就像其他语言中使用集合或变体。你还可以定义一组通用的相关成员为一个枚举,每一种都有不同的一组与它相关的适当类型的值的一部分。
enum CompassPoint {    case North    case South    case East    case West}




0 0
原创粉丝点击