Swift语法 -- [02 - 流程控制]

2020-10-16  本文已影响0人  happy神悦

5. 元组

1. if-else

var age : Int = 30
if age == 30 {
    print("my age is \(age)")
}

2. while

var count = 0
while count<=5 {
    print("num is \(count)")
    count += 1
}

count = 0
repeat {
    print("num is \(count)")
}while count>0

3. for-in

区间运算

// 区间类型
let rang1: ClosedRange<Int> = 1...3
let rang2: Range<Int> = 1..<3
let rang3: PartialRangeThrough<Int> = ...3

for-in常见写法

// 方式一: 默认num是let 类型,可以省略不写
for num in 1...10{
    print(num)
}
// 方式二: 如果要修改 num 的值,需要更改为变量
for var num in 1...10 {
    num += 100
    print(num)
}
// 方式三: 去过不需要用到 num 可以使用_缺省
for _ in 1...10 {
    print("hello,world")
}

// 设置数组的取值范围
let arr2 = ["my", "name", "is", "Alex"]
for str in arr2[1...2] {
    print(str)
}
// 单侧区间运算符
for str in arr2[2...] {
    print(str)
}

// num 的取值:从50开始,累加10,不超过100
let number = 10
for num in stride(from: 50, to: 100, by: number) {
    print(num)
}

4. Switch

switch 与普通 switch 使用类似

注意点:

enum Answer { case right, wrong }
let answer = Answer.right
switch answer {
case .right:
    print("right")
case .wrong:
    print("wrong")
}

let name = "chuan"
switch name {
// 使用, 分割,可以同时判断多个条件,满足一个即执行
case "chuan", "bing":
    print("chuan/bing")
default:
    break
}

// 区间匹配
let count_num = 99
switch count_num {
case 1...10:
    print("1...10")
case 11...20:
    print("11...20")
case 21..<30:
    print("21..<30")
case 30...:
    print(count_num)
default:
    break
}

// 元组匹配
let point = (1, 1)
switch point {
case (0, 0):
    print("the origin")
case (_, 0):
    print("on the x-axis")
case (0, _):
    print("on the y-axis")
case (-2...2, -2...2):
    print("inside the box")
default:
    print("outside of the box")
}

// 值绑定
let point1 = (1, 1)
switch point1 {
case (let x, 0):
    print("the origin is\(x)")
case (let x, let y):
    print("x is \(x), y is \(y)")
case let (x, y):
    print("xxxx is \(x), yyyy is \(y)")
default:
    print("outside of the box")
}

5. where

where用于判断某个条件满足才会进行执行

// for
for num in 1...100 where num % 10 == 0 {
    print(num)
}

// switch
let point2 = (1, 2)
switch point2 {
case let (x, y) where x == y:
    print("x is \(x) y is \(y)")
case let (x, y) where x != y:
    print("xx is \(x) yy is \(y)")
default:
    break
}

上一篇 下一篇

猜你喜欢

热点阅读