您的位置:首页 > 移动开发 > Swift

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!")

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息