流程控制
1.for-in循环
for indexin 1...5 {
//index是一个常量,其值在循环的每次迭代开始时自动设置。因此,索引不必在使用之前声明。
print("\(index) times 5 is\(index * 5)")
}
//如果不需要序列中的每个值,则可以通过使用下划线代替变量名来忽略这些值
let base =3
let power =10
var answer =1
for _ in1...power {
answer *= base
}
print("\(base) to the power of \(power) is\(answer)")//3的 10次幂是 59049
//遍历数组、字典
let names = ["Anna","Alex", "Brian","Jack"]
for namein names {
print("Hello, \(name)!")
}
let numberOfLegs = ["spider":8, "ant": 6, "cat": 4]
for (animalName,legCount)in numberOfLegs {
print("\(animalName)s have\(legCount) legs")
}
2.while循环
while循环执行一组语句,直到条件变为false
while条件 {
语句
}
3.Repeat-While
在考虑循环的条件之前首先执行单次通过循环块。然后继续重复循环,直到条件为假
repeat {
语句
} while 条件
4.条件语句if
var age =15
ifage <= 18 {
print("未成年")
}
ifage <= 6 {
print("该上幼儿园")
} else {
print("该上小学了")
}
5.条件语句switch
switch判断条件 {
case value 1:
对value 1的处理
case value 2,
value 3 :
对value2,3的处理
default:
默认值
}
let someCharacter:Character = "z"
switchsomeCharacter {
case"a":
print("The first letterof the alphabet")
case"z":
print("The last letterof the alphabet")
default:
print("Some othercharacter")
}
//Thelast letter of the alphabet
//注:整个switch语句在第一个匹配开关情况完成后立即完成其执行,而不需要显式break语句。
//虽然在Swift中不需要break,但是可以使用break语句来匹配和忽略特定的案例,或者在案例完成执行之前中断匹配的案例。
let anotherCharacter:Character = "a"
switchanotherCharacter {
case"a"://报错:无效,该案例没有实体值
case"A":
print("The letterA")
default:
print("Not the letterA")
}
//改为:
let anotherCharacter:Character = "a"
switchanotherCharacter {
case"a", "A":
print("The letterA")//Theletter A
default:
print("Not the letterA")
}
2>.间隔匹配
let approximateCount =62
let countedThings ="moons orbiting Saturn"
var naturalCount:String
switchapproximateCount {
case0:
naturalCount = "no"
case1..<5:
naturalCount = "a few"
case5..<12:
naturalCount = "several"
case12..<100:
naturalCount = "dozens of"
case100..<1000:
naturalCount = "hundredsof"
default:
naturalCount = "many"
}
print("There are\(naturalCount)\(countedThings).")//There are dozens of moons orbiting Saturn.
3>.元组匹配
使用元组在同一个switch语句中测试多个值。 可以针对不同的值或值的区间来测试元组的每个元素。或者,使用下划线字符(_)(也称为通配符模式)匹配任何可能的值。
let somePoint = (1,1)
switchsomePoint {
case (0,0):
print("(0, 0) is at theorigin")
case (_,0):
print("(\(somePoint.0), 0) is on thex-axis")
case (0,_):
print("(0, \(somePoint.1)) is on they-axis")
case (-2...2,-2...2):
print("(\(somePoint.0),\(somePoint.1)) is inside thebox")
default:
print("(\(somePoint.0),\(somePoint.1)) is outside of thebox")//(1,1) is inside the box
}
4>.值绑定
将一个或多个匹配的值绑定到临时常量或变量,以在案例的主体中使用。称为值绑定。
let anotherPoint = (2,0)
switchanotherPoint {
case (let x,0):
print("on the x-axiswith an x value of \(x)")//on the x-axis with an x value of 2
case (0, let y):
print("on the y-axiswith a y value of \(y)")
case let (x, y):
print("somewhere else at(\(x),\(y))")
}
5>.where
switch可以使用where子句来检查其他条件
let yetAnotherPoint = (1,-1)
switchyetAnotherPoint {
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")//(1,-1) is on the line x == -y
case let (x, y):
print("(\(x),\(y)) is just somearbitrary point")
}
6>.复合案例
共享同一主体的多个switch case可以通过在每个case之后写入几个模式来组合,在每个模式之间使用逗号。如果任何模式匹配,则认为情况匹配。如果列表很长,则可以在多行上写入模式。
let compoundChar:Character = "e"
switchcompoundChar {
case"a","e","i","o","u"://与英语中的所有五个小写元音相匹配
print("\(compoundChar) is avowel")//eis 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("\(compoundChar) is aconsonant")
default://默认情况下匹配任何其他字符。
print("\(compoundChar) is not avowel or a consonant")
}
7>.控制转移语句
控制转移语句通过将控制从一段代码转移到另一段代码来改变代码执行的顺序。 Swift有五个控制转移语句:
continue
break
fallthrough
return
throw
continue结束当次循环,重新开始下一次迭代循环。
break语句立即结束对整个控制流语句的执行。
fallthroughSwift中的switch语句不会通过每个case的底部,并进入下一个。相反,整个switch语句在第一个匹配大小写完成后立即完成执行。可以根据具体情况选择fallthrough采用关键字逐渐减少的行为。
6.提前退出
//guard语句(如if语句)根据表达式的布尔值执行语句。使用guard语句要求条件必须为真,以便在执行保护语句后的代码。与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 theweather is nice near you.")
return
}
print("I hope theweather is nice in \(location).")
}
greet(person:["name":"John"])//打印 Hello John! I hope the weatheris nice near you.
greet(person:["name":"Jane","location":"Cupertino"])//打印 Hello Jane! I hope the weather is nicein Cupertino.
7.检查API可用性
Swift内置支持检查API可用性,确保您不会意外使用在给定部署目标上不可用的API。
if #available(platformname version, ..., *) {
如果API可用,则执行语句
} else {
如果API不可用,则执行fallback语句
}
if #available(iOS10, macOS 10.12, *) {
//在iOS上使用iOS 10API,并在macOS上使用macOS 10.12 API
} else {
//回到早期的iOS和macOSAPI
}