码迷,mamicode.com
首页 > 编程语言 > 详细

swift基本用法-switch用法

时间:2014-10-21 15:26:06      阅读:220      评论:0      收藏:0      [点我收藏+]

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

swift基本用法-switch用法

标签:swift   switch   判断   

原文地址:http://blog.csdn.net/dylan_lwb_/article/details/40344939

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!