swift控制语句,for,while,repeat-while,if,switch
最后更新于:2022-04-01 11:39:26
if switch for while
~~~
<div>import Foundation
//for循环
for i in 1...5 {
print("(闭区间)标准for in :\(i)")
}
for i in 1..<5 {
print("(半开区间)标准for in :\(i)")
}
//其中 i 是每次循环开始时被自动赋值的常量,这种情况下 i 不需要提前声明,只需要将它包含在循环的声明中,就可以对其进行隐式声明
//如果不需要知道区间内的每一项的值,可以使用下划线 _ 替代变量名来忽略对值的访问
var result1 = 1
for _ in 1...5 {
result1 *= 2
}
print("for 不访问每一项的值:\(result1)")
//for in 遍历数组
var indexs = ["111", "222", "333"]
for index in indexs {
print("for 遍历数组:\(index)")
}
//for in 遍历字典
var dicts = ["key1":"value1", "key2":"value2", "key3":"value3"]
for (key, value) in dicts {
print("for 遍历字典:\(key) : \(value)")
}
//标准for循环
for var i = 0; i < 3; i++ {
print("标准for循环:\(i)")
}
//while循环
var i = 0
while i < 3 {
print("标准while:\(i)")
i++
}
// i 需要定义并且初始化
//repeat-while
//先执行循环体,再执行条件语句 类似于do while
var j = 0
repeat {
print("repeat while : \(j)")
j++
} while j < 3
//if 语句
var age = 10
if age < 10 {
print("年龄小于10")
}else if age == 10 {
print("年龄等于10")
}else {
print("年龄大于10")
}
//switch 语句
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")
}
//与 C 语⾔和 Objective-C 中的 switch 语句不同,在 Swift 中,当匹配的 case 分⽀中的代
//码执⾏完毕后,程序会终⽌ switch 语句,⽽不会继续执⾏下⼀个 case 分⽀。这也就是
//说,不需要在 case 分⽀中显式地使⽤ break 语句。这使得 switch 语句更安全、更易⽤,也
//避免了因忘记写 break 语句⽽产⽣的错误。
//switch 匹配区间
let day = 1234
switch day {
case 1...100: //... 闭区间
print("这个天数很小")
case 101..<1_000: //..< 半开区间
print("这个天数不小了")
case 1_000...10_000:
print("这个天数有点大")
default:
print("不知道这个天数在哪个区间")
}</div>
~~~
输出:
~~~
<div>(闭区间)标准for in :1
(闭区间)标准for in :2
(闭区间)标准for in :3
(闭区间)标准for in :4
(闭区间)标准for in :5
(半开区间)标准for in :1
(半开区间)标准for in :2
(半开区间)标准for in :3
(半开区间)标准for in :4
for 不访问每一项的值:32
for 遍历数组:111
for 遍历数组:222
for 遍历数组:333
for 遍历字典:key1 : value1
for 遍历字典:key3 : value3
for 遍历字典:key2 : value2
标准for循环:0
标准for循环:1
标准for循环:2
标准while:0
标准while:1
标准while:2
repeat while : 0
repeat while : 1
repeat while : 2
年龄等于10
e is a vowel
这个天数有点大
Program ended with exit code: 0</div>
~~~