swift-switch使用方法

// 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 += "整数"
}

原文地址:https://www.cnblogs.com/mfrbuaa/p/5095072.html