Swift-5(控制流)

2020-07-13  本文已影响0人  雨亦有种执着

每日一句:

不积跬步,无以至千里;不积小流,无以成江海

一、for-in循环

for item in items {
    code
}

事例:

//遍历数组
var nameArray = [String]()
nameArray = ["king","jone","kitty","bob","rob"]
for obj in nameArray {
    print(obj)
}
for (index,obj) in nameArray.enumerated() {
    print("my name is \(obj), sit at \(index)")
}
//遍历字典
var nameDic = ["name":"king","age":"100"]
for obj in nameDic {
    print(obj)
}
for obj in nameDic.keys {
    print(obj)
}
for obj in nameDic.values {
    print(obj)
}
for (index,obj) in nameDic.enumerated() {
    print("我有一个对象\(obj.key),在咖啡厅第\(index)位等我😯")
}
//遍历set
var nameSet:Set<String> = ["king","jone","kitty"]
for obj in nameSet {
    print(obj)//kitty、king、jone
    //从打印结果可以看出set是无序的
}
for (index,obj) in nameSet.enumerated() {
    print("my name is \(obj), sit at \(index)")
}
//遍历字符串的字符
var name = "king"
for obj in name {
    print(obj)//k、i、n、g
}
//遍历区间数据
for index in 1...5 {
    print(index)
}
for index in 1..<5 {
    print(index)
}
//从0-10,每新增1,做一件事
for obj in stride(from: 0, to: 10, by: 1) {
    print("do something at \(obj)")
}

二、while循环

while condition {
    code
}
repeat {
    code
} while condition

事例:

var a = 1;
let b = 3;
while a < b {
    a+=1
    print(a)
}
repeat {
    a-=1
    print(a)
} while a>=b

三、if条件语句

事例:

if a < b {
    print("maxvalue is \(b)")
}

四、switch语句

事例:

let someCharacter: Character = "z"
switch someCharacter {
case "a": break
case "z":
    print("你好")
case "y": break
default:
    print("hello")
}
switch someCharacter {
case "a","y": break
case "z" :
    print("helloz")
default:
    break
}

gitHub地址:(https://github.com/kingbroad/SwiftStudy)(欢迎👏关注❤️)

上一篇 下一篇

猜你喜欢

热点阅读