写在最前
鉴于本人此时此刻对Swift和OC的了解尚浅,还有许多需要学习的地方,本文也只是单纯的学习笔记,如果哪里写得不对,望不吝指出!本人乐于接受批评指点,并珍惜共同探讨的机会!
正文
发现
Swift和OC的控制流基本一样,有while、if、switch、for-in、break、continue...,区别只在于语法和一些小地方,下文会列举。在学习的过程中,我发现了两个在OC中没有用过的控制流关键词--fallthrough和guard。另外,还有个叫Labeled Statements的东东,下面来一起探索一下吧!
Fallthrough
为了方便说明,下面在switch场景中描述fallthrough的用法。
在Swift中,switch语句在执行完某个case之后就会完成整个语句的执行,不会再执行其他case。如果你想执行switch中的多个case,那么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."
}
print(description)
// Prints "The number 5 is a prime number, and also an integer."
在上面的例子中,我们发现,代码不单执行了第一个case,还执行了default,但需要澄清的是,fallthrough的作用并不是从某个case跳到default,而是继续执行下一个case,与下一个case的条件无关,这点特地指出。
Guard
Guard语句,与if语句类似,都是根据表达式的布尔值来执行语句。但与if语句不同的是,guard语句总是伴有一个else子句,即如果条件不成立,则执行else子句中的代码。
上例子:
func greet(person: [String: String]) {
guard let name = person["name"] else {
return
}
print("Hello \(name)!")
guard let location = person["location"] else {
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in \(location).")
}
greet(person: ["name": "John"])
// Prints "Hello John!"
// Prints "I hope the weather is nice near you."
greet(person: ["name": "Jane", "location": "Cupertino"])
// Prints "Hello Jane!"
// Prints "I hope the weather is nice in Cupertino."
从上面的例子中,我们可以发现guard其实有点像现实生活中的小区保安,区别在于黑白分明。需要注意的是,guard的else子句中必须要写退出本函数的代码,如return,break,continue或throw,也可以调用不返回的函数或方法,例如:
fatalError(_:file:line:)
与使用if语句进行同样的检查相比,使用guard能使代码更可读。它可以让代码更简洁,并且可以阻挡不符合条件的代码执行。
Labeled Statements
好东东啊!按我的理解就是给控制语句起了个名字,让我们能更好地玩耍!上例子!重点在“gameLoop”!
gameLoop: while square != finalSquare {
switch *** {
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
do sth
}
}
print("Game over!")
下文为了简洁,只列举Swift与OC在for-in、while、if、switch中,用法不同的小地方。
For-In Loops
1.给键与值命名,可以方便使用
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// spiders have 8 legs
// cats have 4 legs
2.结合闭范围运算符(...)使用,若index常量不需要用到,可以用下划线(_)替代,如:
for index in 1...5 {
print("\(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
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// Prints "3 to the power of 10 is 59049"
更多用法:
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
// render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}
let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
// render the tick mark every 3 hours (3, 6, 9, 12)
}
While
Swift中将while分为while和repeat-while,与OC中的while和do-while一样,区别在于“先判断后执行”,或是“先执行后判断”,不做赘述。
If
没什么不同的用法,与OC基本一致。
Switch
用法更简洁方便了,break可以省略,如以下例子:
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
// Prints "The letter A"
let approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
naturalCount = "no"
case 1..<5:
naturalCount = "a few"
case 5..<12:
naturalCount = "several"
case 12..<100:
naturalCount = "dozens of"
case 100..<1000:
naturalCount = "hundreds of"
default:
naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
print("\(somePoint) is at the origin")
case (_, 0):
print("\(somePoint) is on the x-axis")
case (0, _):
print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
print("\(somePoint) is inside the box")
default:
print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
print("on the x-axis with an x value of \(x)")
case (0, let y):
print("on the y-axis with a y value of \(y)")
case let (x, y):
print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
print("(\(x), \(y)) is just some arbitrary point")
}
// Prints "(1, -1) is on the line x == -y"
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
print("\(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":
print("\(someCharacter) is a consonant")
default:
print("\(someCharacter) is not a vowel or a consonant")
}
// Prints "e is a vowel"
let stillAnotherPoint = (9, 0)
switch stillAnotherPoint {
case (let distance, 0), (0, let distance):
print("On an axis, \(distance) from the origin")
default:
print("Not on an axis")
}
// Prints "On an axis, 9 from the origin"
小结
Swift在条件的书写上简洁了许多,希望大家用得愉快!
参考文献