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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值