// Playground - noun: a place where people can play
import UIKit
//------------------------------------------------------------------------------
// 1. 基本使用
// switch 与OC的区别:
// 1> 不需要写break
// 2> 每个分支条件中的指令不能不写
// 3> case如果取多值时,可以使用","分隔
var grand = "a"
var result:String
switch 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 = 20
var str = "\(num)是 "
switch num {
case 0...50:
str += "0~50之间的 "
fallthrough
default :
str += "整数"
}
swift switch用法
最新推荐文章于 2024-04-29 00:15:00 发布