加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 01:29:38 所属栏目:百科 来源:网络整理
导读: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"
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++ {
"(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 {
(chare)
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读