swift-switch用法

来源:互联网 发布:sql server 2008注册码 编辑:程序博客网 时间:2024/05/18 03:39
// Playground - noun: a place where people can playimport UIKit//------------------------------------------------------------------------------// 1. 基本使用// switch 与OC的区别:// 1> 不需要写break// 2> 每个分支条件中的指令不能不写// 3> case如果取多值时,可以使用","分隔var grand = "a"var result:Stringswitch grand.uppercaseString {    case "A":        result = "优等 \(grand)"    case "B":        result = "良"    case "C":        result = "中"    case "D", "E", "F":        result = "差"    default:result = "未知"}//------------------------------------------------------------------------------// 2. 变量/常量赋值// 在case匹配的同时,可以将switch中的值绑定给一个特定的常量或者变量,以便在case的语句中使用var point = (10, 10)switch point {case (let x, 0) :    result = "这个点在x轴上, x值是\(x)"case (0, let y) :    result = "这个点在y轴上, y值是\(y)"case let (x, y) :    result = "这个点的x值是\(x), y值是\(y)"}//------------------------------------------------------------------------------// 3. where// 使用where可以增加判断条件var point1 = (10, -10)switch point1 {case let (x, y) where x == y :    result = "在 \\ 对角线上"case let (x, y) where x == -y :    result = "在 / 对角线上"default :    result = "不在对角线上"}//------------------------------------------------------------------------------// 4. fallthrough// 在执行完当前case后,继续执行后面的case或者default语句var num = 20var str = "\(num)是 "switch num {case 0...50:    str += "0~50之间的 "    fallthroughdefault :    str += "整数"}

0 0
原创粉丝点击