Swift - 控制流/控制结构说明(if,switch,for,while)

前端之家收集整理的这篇文章主要介绍了Swift - 控制流/控制结构说明(if,switch,for,while)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1,if语句
1
2
3
4
5
if count >=3 {
print ( "yes" )
} else {
"no" )
}

2,switch语句
(1)Swift中不需要在case块中显示地使用break跳出switch。如果想要实现C风格的落入特性,可以给需要的case分支插入fallthrough语句
5
6
7
8
9
10
let fruit = "apple"
switch fruit{
case "apple" :
"good" fallthrough
"banana" , "orange" :
"great" )
default :
"bad" )
}
(2)case分支还可以进行区间匹配
9
age = 5
age {
case 0...11:
"正太" 12...30:
"少年" )
:
"大叔" )
}
(3)使用元组匹配(判断属于哪个象限)
10
11
12
13
point = (2,2)
point {
(0,0):
"坐标在原点" (_,0):
"坐标在x轴上" "坐标在y轴上" (-3...3,-3...3):
"坐标在长宽为6的正方形内" )
:
"在什么地方" )
}
(4)case中还可以使用where关键字来做额外的判断条件
varheight = 1.72
height{
1...3 where height == 1.72:
"case 1" height == 2:
"case 2" "default" }

3,for循环语句
(1)for条件递增循环
3
for i=1; i<100; i++ { @H_718_301@"\(i)" }
(2)for-in循环
13
14
15
16
17
18
19
20
for i in 1..<100{
}
//遍历数组元素
numbers = [1,2,4,7]
num numbers{
"\(num)" }
//遍历字典
nameOfAge = [ "lily" :18,monospace!important; min-height:inherit!important; color:blue!important">"Candy" :24]
(aName,iAge) nameOfAge{
"\(aName) is \(iAge)" )
}
//遍历字符串的字符
chare in "hangge" .characters {
@H_799_404@(chare)
}

4,while循环语句
7
while i<100 {
i++
repeat{
i++
i<100

原文出自: www.hangge.com 转载请保留原文链接 http://www.hangge.com/blog/cache/detail_516.html

猜你在找的Swift相关文章