Swift-基础语法
Swift-基础语法
Swift-基础语法
1 简单if
1
2
3
if someCondition {
print("Do something")
}
1
2
3
if speed >= 88 {
print("Where we're going we don't need roads.")
}
1
2
3
4
5
6
7
8
9
10
enum Sizes: Comparable {
case small
case medium
case large
}
let first = Sizes.small
let second = Sizes.large
print(first < second)
// “true”,因为枚举类型列表中 small 在 large 之前。
2 多条件if
2.1. if-else
1
2
3
4
5
if someCondition {
print("This will run if the condition is true")
} else {
print("This will run if the condition is false")
}
2.2. if-else if
1
2
3
4
5
6
7
8
9
10
let a = false
let b = true
if a {
print("Code to run if a is true")
} else if b {
print("Code to run if a is false but b is true")
} else {
print("Code to run if both a and b are false")
}
2.3. 多条件if
1
2
3
4
5
6
7
8
9
if temp > 20 && temp < 30 {
print("It's a nice day.")
}
if userAge >= 18 || hasParentalConsent == true {
print("You can buy the game")
}
if (isOwner == true && isEditingEnabled) || isAdmin == true {
print("You can delete this post")
}
3 switch 语句检查多个条件
3.1. 基础
Swift 会按顺序检查所有 case,并执行第一个匹配的 case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
enum Weather {
case sun, rain, wind, snow, unknown
}
switch forecast {
case .sun:
print("It should be a nice day.")
case .rain:
print("Pack an umbrella.")
case .wind:
print("Wear something warm")
case .snow:
print("School is cancelled.")
case .unknown:
print("Our forecast generator is broken!")
default:
print("Who are you?")
}
3.2. fallthrough
继续执行后续的 case
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
let day = 5
print("My true love gave to me…")
switch day {
case 5:
print("5 golden rings")
fallthrough
case 4:
print("4 calling birds")
fallthrough
case 3:
print("3 French hens")
fallthrough
case 2:
print("2 turtle doves")
fallthrough
default:
print("A partridge in a pear tree")
}
1
2
3
4
5
6
My true love gave to me...
5 golden rings
4 calling birds
3 French hens
2 turtle doves
A partridge in a pear tree
4 什么时候应该使用 switch 语句而不是 if 语句?
以下三个原因可能会让你考虑使用 switch 而不是 if :
- Swift 要求
switch语句必须穷尽所有可能的情况,这意味着你必须为每个可能的值都编写一个case代码块(例如枚举类型的所有情况),或者必须有一个default情况。ififelse if则没有这样的限制,因此你可能会意外地遗漏某些情况。 - 当你使用
switch检查某个值是否存在多个可能的结果时,该值只会读取一次;而如果你使用if,则会读取多次。这一点在开始使用函数调用时尤为重要,因为有些函数调用速度较慢。 - Swift 的
switch语句允许进行高级模式匹配,而if则难以做到这一点
5 三元运算符
1
2
let hour = 23
print(hour < 12 ? "It's before noon" : "It's after noon")
6 for 循环
6.1. 基础
1
2
3
4
5
let platforms = ["iOS", "macOS", "tvOS", "watchOS"]
for os in platforms {
print("Swift works great on \(os).")
}
遍历固定范围的数字
1 2 3 4
for i in 1...12 { print("5 x \(i) is \(5 * i)") } // 1~12
1 2 3 4
for i in 1..<5 { print("Counting 1 up to 5: \(i)") } //1~4
使用一个范围运行一些代码若干次
Swift 会识别出你实际上并不需要该变量,因此不会为你创建临时常量
1 2 3 4 5 6
var lyric = "Haters gonna" for _ in 1...5 { lyric += " hate" } print(lyric) //Haters gonna hate hate hate hate hate
6.2. 范围运算符...、..<
便于便利数组
1
2
3
4
let names = ["Piper", "Alex", "Suzanne", "Gloria"]
print(names[1...3])
print(names[1...])
//["Alex", "Suzanne", "Gloria"]
本文由作者按照 CC BY 4.0 进行授权