swift 系统学习 07 区间 和 switch case
2017-03-01 15:09
253 查看
//: Playground - noun: a place where people can play import UIKit /* * 本节内容: switch语句 * 1.基本使用 * 2.和区间运算符结合 * 3.和元组结合 * 4.where模式匹配 */ /* C语言的switch语句: 条件只能判断int类型 * switch (条件) { case 条件1整型: 语句; break; case 条件2整型: case 条件3整型: case 条件4整型: 语句; break; default: break; } */ // 基本使用 // ctl + i: 自动代码格式化 let rating = "A" // 判定字符串 switch rating { case "A", "a": print("Great!") case "B", "b": print("Just so so!") case "C", "c": print("It's not good") default: print("No rating!") } // 和区间运算符的结合 var score = 93 // 整型 switch score { case 90...100: print("Score is A!") case 80...89: print("Score is B!") case 70...79: print("Score is C!") default: print("Score is not good") } // 需求: 判定二维坐标系的点, 是否是单元向量(1,0),(0, -1),(-1, 0), (0,1) let vector = (1, 0) switch vector { case (0, 0): print("The point is origin!") case (1, 0): print("It is the unit vector on the positive x-axis!") case (-1, 0): print("It is the unit vector on the negative x-axis!") case (0, 1): print("It is the unit vector on the positive y-axis!") case (0, -1): print("It is the unit vector on the negative y-axis!") default: print("It is the ordinary point.") } // 需求: 判定二维坐标系的点在x轴上(y=0), 还是y轴上(x=0) let point2D = (10, 0) switch point2D { case (_, 0): print("It is on the x-axis!") case (0, _): print("It is on the y-axis!") case (-1...1, -1...1): print("It is near to the origin!") default: print("It is ordinary point!") } // switch中的值绑定(value binding): 使用常量来接收元组分量的值 // 如果已经穷举所有case可能性, 不需要写default语句 switch point2D { case (let x, 0): print("The x value is \(x)") // x的作用域仅在case内 case (0, let y): print("The y value is \(y)") case (let x, let y): print("The point is (\(x), \(y))") } /* SQL语句: 有条件查询语句 * select * from tableName where name="gaoyuanyuan" * 需求: 判定两位坐标系的点是否在两条直线上: y=x; y=-x */ switch point2D { case let (x, y) where x == y: print("The point is on the line x==y!") case let (x, y) where x == -y: print("The point is on the line x==-y!") default: print("The point is ordinary point!") }
相关文章推荐
- swift 系统学习 03 三目 区间运算符 开区间 闭区间 和三目类似的还有一个空合/聚合运算符
- Swift 系统学习 01 系统学习 01 常量 变量 (Objective-C)
- Swift 系统学习 09 repeat while
- Swift 系统学习 18 结构体 改变结构体里面的元素
- S008 - iOS 应用基础 swift版 - 系统学习 iOS 界面编程
- 学习swift从青铜到王者之swift枚举07
- swift 系统学习 06 循环语句
- Swift 系统学习 10 字典 Dictionary 增删改查
- Swift 系统学习 19 结构体的默认构造方法和自定义构造方法
- swift学习笔记 - 判断当前运行的系统和平台
- swift 系统学习 06 循环语句
- Swift 系统学习 20 结构体 添加可失败的构造方法
- Swift 系统学习 31 扩展 extension
- Swift 系统学习 34 线程通信 Swift3.0 子线程下载图片主线程显示图片
- swift学习笔记 - 判断当前运行的系统和平台
- 推荐系统学习07-Waffles
- swift 系统学习 06 循环语句
- swift 系统学习 06 循环语句
- Swift 系统学习 11 函数 函数的声明 和调用 下划线 调用的时候 忽略参数名
- Swift 系统学习 21 存储型属性和计算型属性 下标语法