-
For-In循环 ( For-In Loops)
使用for-in循环遍历序列,例如数组中的项、数字范围或字符串中的字符。
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
print("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex!
// Hello, Brian!
// Hello, Jack!
您还可以遍历字典以访问其键值对。 当遍历字典时,字典中的每个项目都作为(键,值)元组返回,并且您可以将(键,值)元组的成员分解为显式命名的常量,以便在for-in循环的主体内使用。
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
print("\(animalName)s have \(legCount) legs")
}
// ants have 6 legs
// cats have 4 legs
// spiders have 8 legs
您还可以使用带数值范围的for-in循环
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"
在某些情况下,您可能不希望使用包含两个端点的封闭范围。 考虑在表盘上绘制每分钟的刻度线。 你想绘制60
个刻度线,从0
分钟开始。 使用半开范围运算符(.. <)
包括下限但不包括上限。
let minutes = 60
for tickMark in 0..<minutes {
// render the tick mark each minute (60 times)
}
某些用户可能希望其UI中的刻度标记更少。 他们可能更喜欢每5分钟一个标记。 使用stride(from:to:by :)
函数跳过不需要的标记。
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)
}
也可以使用stride(from:through:by:)
代替:
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循环 (While Loops)**
1.while
while
循环从评估单个条件开始。 如果条件为真,则重复一组语句,直到条件变为false
。
这是while
循环的一般形式:
while condition {
statements
}
2.Repeat-While
while
循环的另一种变体,称为repeat-while
循环,在考虑循环的条件之前,首先执行一次遍历循环块的操作。然后它继续重复该循环,直到条件为false
为止。
NOTE
Swift中的repeat-while循环类似于其他语言中的do-while循环。
repeat {
statements
} while condition
-
条件语句 (Conditional Statements)
1.if
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
}
// Prints "It's very cold. Consider wearing a scarf."
对于if
条件为false
的情况,if
语句可以提供另一组语句,称为else
子句。 这些语句由else
关键字指示。
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's not that cold. Wear a t-shirt."
您可以将多个if语句链接在一起以考虑附加子句。
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
} else {
print("It's not that cold. Wear a t-shirt.")
}
// Prints "It's really warm. Don't forget to wear sunscreen."
但是,最后的else
子句是可选的,如果不需要完成条件集,则可以排除该子句。
temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
print("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
print("It's really warm. Don't forget to wear sunscreen.")
}
-
Switch
1.简单的swift
在最简单的形式中,switch
语句将值与一个或多个相同类型的值进行比较。
switch some value to consider {
case value 1:
respond to value 1
case value 2,
value 3:
respond to value 2 or 3
default:
otherwise, do something else
}
此示例使用switch
语句来考虑名为someCharacter
的单个小写字符:
let someCharacter: Character = "z"
switch someCharacter {
case "a":
print("The first letter of the alphabet")
case "z":
print("The last letter of the alphabet")
default:
print("Some other character")
}
// Prints "The last letter of the alphabet"
2.No Implicit Fallthrough
每个案例的主体必须包含至少一个可执行语句。 编写以下代码无效,因为第一种情况为空
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
print("The letter A")
default:
print("Not the letter A")
}
// This will report a compile-time error.
要使用与“a”
和“A”
匹配的单个案例进行切换,请将这两个值组合成一个复合案例,用逗号分隔值。
let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
print("The letter A")
default:
print("Not the letter A")
}
// Prints "The letter A"
3.区间匹配
可以检查切换情况中的值是否包含在间隔中。 此示例使用数字间隔为任意大小的数字提供自然语言计数:
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."
4.元组
您可以使用元组在同一个switch
语句中测试多个值。 可以针对不同的值或值的间隔来测试元组的每个元素。 或者,使用下划线字符(_)
(也称为通配符模式)来匹配任何可能的值。
下面的示例采用(x,y)
点,表示为类型(Int,Int)
的简单元组,并将其分类在示例后面的图表上。
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"
image.png
5.值绑定
switch case
可以将它匹配的值命名为临时常量或变量,以便在case
的主体中使用。 此行为称为值绑定,因为值绑定到案例正文中的临时常量或变量。
下面的示例采用(x,y)
点,表示为类型(Int,Int)
的元组,并将其分类在下面的图表上:
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"
image.png
6.Where
switch case
可以使用where
子句来检查其他条件。
以下示例对下图中的(x,y)
点进行了分类:
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"
image.png
7.复合案例
可以通过在大小写之后写入多个模式来组合共享相同主体的多个开关案例,每个模式之间使用逗号。 如果任何模式匹配,则认为该情况匹配。 如果列表很长,则可以在多行上写入模式。 例如:
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"
-
控制转移语句 ( Control Transfer Statements)
continue
break
fallthrough
return
throw
Continue
continue
语句告诉循环停止它正在做什么,并在循环的下一次迭代开始时再次启动。 它说“我完成了当前的循环迭代”而没有完全离开循环。
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
let charactersToRemove: [Character] = ["a", "e", "i", "o", "u", " "]
for character in puzzleInput {
if charactersToRemove.contains(character) {
continue
}
puzzleOutput.append(character)
}
print(puzzleOutput)
// Prints "grtmndsthnklk"
Break
break
语句立即结束整个控制流语句的执行。 当你想要比其他情况更早地终止switch
或loop
语句的执行时,可以在switch
或loop
语句中使用break
语句。
1.在循环语句中中断(Break in a Loop Statement)
在循环语句中使用时,break
会立即结束循环的执行,并在循环的右括号(})
之后将控制权转移给代码。 不执行来自当前循环迭代的进一步代码,并且不再开始循环的迭代。
2.中断Switch
语句 (Break in a Switch Statement
)
let numberSymbol: Character = "三" // Chinese symbol 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 {
print("The integer value of \(numberSymbol) is \(integerValue).")
} else {
print("An integer value could not be found for \(numberSymbol).")
}
// Prints "The integer value of 三 is 3."
Fallthrough
如果需要c风格的fallthrough行为,可以使用fallthrough关键字根据具体情况选择该行为。下面的示例使用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."
标签语句
一个带标签的语句通过将一个标签放在与该语句的介绍人关键字相同的行上,然后加上一个冒号来表示。下面是一个while
循环的语法示例,尽管所有循环和switch
语句的原则都是相同的:
label name: while condition {
statements
}
gameLoop: while square != finalSquare {
diceRoll += 1
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]
}
}
print("Game over!")
-
提前退出 ( Early Exit)
与if语句一样,guard
语句根据表达式的布尔值执行语句。 您使用guard
语句要求条件必须为true
才能执行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 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."
-
检查API可用性 ( Checking API Availability)
您可以在if
或guard
语句中使用可用性条件来有条件地执行代码块,具体取决于您要使用的API
是否在运行时可用。 当编译器验证该代码块中的API
可用时,编译器将使用可用性条件中的信息。
if #available(iOS 10, macOS 10.12, *) {
// Use iOS 10 APIs on iOS, and use macOS 10.12 APIs on macOS
} else {
// Fall back to earlier iOS and macOS APIs
}
在一般形式中,可用性条件采用平台名称和版本的列表。 您可以使用iOS,macOS,watchOS
和tvOS
等平台名称作为完整列表,请参阅声明属性。 除了指定主要版本号(如iOS 8或macOS 10.10)
之外,您还可以指定次要版本号,如iOS 11.2.6
和macOS 10.13.3
。
if #available(platform name version, ..., *) {
statements to execute if the APIs are available
} else {
fallback statements to execute if the APIs are unavailable
}
网友评论