【swift-总结】控制流
2015-06-27 08:57
429 查看
for语句
//使用范围 for index in 1...5 { print(index); }
//如果不需要使用循环变量,可以使用下划线替代 var time = 5; var i = 0 for _ in 1...time { print("第\(++i)次"); }
//遍历数组 let numbers = ["one", "two", "three"]; for number in numbers { print(number); }
//遍历字典 let numStr = ["one": 1, "two": 2, "three": 3]; for (str, num) in numStr { print("\(str) is \(num)"); }
//遍历字符串的字符 for character in "hello".characters { print(character); }
//经典for循环 for var i=0; i<5; i++ { print(i); }
//新型for循环 for i in 0..<3 { forstLoop += i; } 相等于 for var i=0; i<3; i++ { forstLoop += i; }
switch语句
switch默认没有穿透功能,不需要加break。如果要有穿透要使用fallthroughlet num = "one" switch num { case "one": print("one"); case "two": print("two") default: print("错误"); }
switch num { case "one", "two": print("你好"); default: print("不好"); }
//使用范围 let score = 88; switch score { case 0...60: print("不及格"); case 60...70: print("中等"); case 70...80: print("良好"); case 80...100: print("优秀"); default: print("超鬼"); }
//使用点 let point = (1, 1) switch point { case (0, 0): print("原点"); case (_, 0): print("x轴上的点"); case (0, _): print("Y轴上的点"); default: print("普通点"); }
赋值
let anotherPoint = (2, 0); switch anotherPoint { case (let x, 0): print("在X轴上面的点是\(x)"); case (0, let y): print("在Y轴上面的点是\(y)"); case let(x, y): print("其他点(\(x), \(y))"); }
还可以加where条件,有赋值的时候不能使用default
let wherePoint = (-1, -1); switch wherePoint { case let(x, y) where x == y: print("x=y的点是(\(x), \(y))" ); case let(x, y) where x == -y: print("x=-y的点是(\(x), \(y))"); case let (x, y): print("其他的两个点") }
另外还有continue,break,return,do-while,while,if语句都与其他语言类似
相关文章推荐
- swift 类型转换
- swift初体验
- IOS/swift 异步缓存文件
- 拥抱Swift吧,骚年!
- 从零开始--系统深入学习IOS(使用Swift---带链接)
- ios swift模仿qq登陆界面,xml布局
- ios swift模仿qq登陆界面,xml布局
- Swift AVFoundation 二维码扫描和生成
- Swift入坑--block的定义
- SWIFT中计算两个日期间隔多少小时
- [教程技巧] 简析Swift和C的交互
- Swift函数
- Swift控制语句
- 源码推荐(6.26):三级联想菜单(也可以当二级),tableView reloadData动画(swift)
- Swift单例
- 6.25 android开发mvp模式,类似swift的jvm语言kotlin
- SWIFT显示底部的工具条
- Swift项目的main函数为何消失了?如何把它找出来?
- Swift字典
- Swift的数组