swift

Swift基础1(流程控制)

2019-11-17  本文已影响0人  SunshineBrother

if-else

let score = 88
if score > 80 {
    print("优秀")
}else if score > 60{
    print("及格")
}else{
    print("不及格")
}

if-else.png

while

var num = 5
while num > 0 {
    print(num)
    num -= 1
} //打印5次

for

区间运算符

用法1

let names = ["name1","name2","name3","name4"]
for i in 0...3 {
    print(names[i])
}

打印
name1
name2
name3
name4

用法2

let names = ["name1","name2","name3","name4"]
let range = 1...3
for i in range {
    print(names[i])
}

打印
name2
name3
name4

用法3

i默认是let,有需要的时候也可以声明为var

for var i in 1...3 {
    i += 5
    print(i)
}

打印
6
7
8

用法4

单侧区间:让区间朝一个方向尽可能的远

let names = ["name1","name2","name3","name4"]
for name in names[1...] {
    print(name)
}

name2
name3
name4

for name in names[...2] {
    print(name)
}

name1
name2
name3

用法5

区间类型

let range1: ClosedRange<Int> = 0...5
let range2: Range<Int> = 0..<5
let range3: PartialRangeThrough<Int> = ...5
let range1 = ...5
range1.contains(7) false
range1.contains(3) true

字符,字符串也能使用区间运算符,但默认不能用在for-in

let range2 = "aa"..."ff"
range2.contains("af")   true
range2.contains("zz")   false
range2.contains("az")   true

用法6
带间隔的区间值

let hours = 11
let interval = 2
for tickMark in stride(from: 4, to: hours, by: interval) {
    print(tickMark)
}
4
6
8
10

switch

let num = 1
switch num {
case 1:
    print("num is \(num)")
    print("num is \(num)")
    print("num is \(num)")
case 2:
    print("num is \(num)")
default:
    break
}

fallthrough
使用fallthrough可以实现贯穿效果

let num = 1
switch num {
case 1:
    print("num is 1")
    fallthrough
case 2:
    print("num is 2")
default:
    break
}


num is 1
num is 2

符合条件

switch支持多个条件一起判断

let a = "json"
switch a {
case "json","xml":
    print("json or xml")
case "text":
    print("text")
default:
    break
}

区间匹配,元祖匹配

可以使用_忽略某个值

let point = (1,1)
switch point {
case (0,0):
    print("(0,0)")
case (_,1):
    print("(_,1)")
case (2,1):
    print("(_,1)")
default:
    break
}

(_,1)

也可以使用区间匹配

let point = (1,1)
switch point {
case (0,0):
    print("(0,0)")
case (-1...1,-1...1):
    print("(-1...1,-1...1)")
case (2,1):
    print("(_,1)")
default:
    break
}

(-1...1,-1...1)

值绑定

let point = (1,1)
switch point {
case (0,0):
    print("(0,0)")
case (let x,1):
    print("x is \(x)")
case (2,1):
    print("(_,1)")
default:
    break
}

x is 1

必要的时候,let可以改为var

where

where其实就是多加的控制条件

let list = [1,-10,5,-7]
for num in list where num > 0 {
    print(num)
}

1
5
上一篇下一篇

猜你喜欢

热点阅读