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

一、if 语句

if count >= 3 {
    print("yes")
}else{
    print("no")
}

二、switch 语句

(1)Swift中不需要在case块中显示地使用break跳出switch。如果想要实现C风格的落入特性,可以给需要的case分支插入fallthrough语句 //alphaZ

let fruit = "apple"
switch fruit{
    case "apple":
        print("good")
        fallthrough
    case "banana","orange":
        print("great")
    default:
        print("bad")
}

(2)case分支还可以进行区间匹配 //alphaZ

let age = 5
switch age {
    case 0...11:
        print("正太")
    case 12...30:
        print("少年")
    default:
        print("大叔")
}

(3)case分支同样支持单侧区间匹配 //alphaZ

let num = -5
switch num {
case ..<0:
    print("负数")
case 0:
    print("0")
case 0...:
    print("正数")
default:
    print("未知")
}

(4)使用元组匹配(判断属于哪个象限)//alphaZ

let point = (2,2)
switch point {
    case (0,0):
        print("坐标在原点")
    case (_,0):
        print("坐标在x轴上")
    case (0,_):
        print("坐标在y轴上")
    case (-3...3, -3...3):
        print("坐标在长宽为6的正方形内")
    default:
        print("在什么地方")
}

(4)case中还可以使用where关键字来做额外的判断条件 //alphaZ

var height = 1.72
switch height{
    case 1...3 where height == 1.72:
        print("case 1")
    case 1...3 where height == 2:
        print("case 2")
    default:
        print("default")
}

三、for 循环语句

(1)for条件递增循环(注意:这种C语言风格的for循环语法已在Swift3中被废除,建议使用下面的for-in,for-each写法)

//已弃用
//for var i=1; i<100; i++ {
//  print("\(i)")
//}

(2)for-in循环

for i in 1..<100{
    print("\(i)")
}
 
//遍历数组元素
let numbers = [1,2,4,7]
for num in numbers{
    print("\(num)")
}
 
//遍历字典
let nameOfAge = ["lily":18, "Candy":24]
for (aName, iAge) in nameOfAge{
    print("\(aName) is \(iAge)")
}
 
//遍历字符串的字符
for chare in "hangge".characters {
    print(chare)
}
(3)for-each循环

(1...10).forEach {
    print($0)
}

特殊用法

1.要遍历数组同时拿到下标值和元素,可通过元祖进行遍历

1.1 定义数组一个字符串数组如下

let array: [String] = ["a","b","c","d"]

1.2 利用元祖进行遍历
for (index,value) in array.enumerated() {

        print(index,value)

    }

1.3 输出结果为

0 a

1 b

2 c

3 d

2.1 若要对数组进行反向遍历,可使用reversed()方法如下

for (index,value) in array.enumerated().reversed() {

        print(index,value)

    }

2.2 输出结果如下

3 d

2 c

1 b

0 a

四、while 循环语句

while i<100 {
    i+=1
}
 
repeat{
    i+=1
}while i<100

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容