// 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
str += "整數"
本文轉自mfrbuaa部落格園部落格,原文連結:http://www.cnblogs.com/mfrbuaa/p/5095072.html,如需轉載請自行聯系原作者