swift 系统学习 07 区间 和 switch case

本文详细介绍了Swift语言中switch语句的各种用法,包括基本使用、与区间运算符结合、与元组结合以及where模式匹配等高级特性,并通过实例进行讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//: Playground - noun: a place where people can play

import UIKit

/*
 * 本节内容: switch语句
 * 1.基本使用
 * 2.和区间运算符结合
 * 3.和元组结合
 * 4.where模式匹配
 */

/* C语言的switch语句: 条件只能判断int类型
 * switch (条件) {
     case 条件1整型:
       语句;
       break;
     case 条件2整型:
     case 条件3整型:
     case 条件4整型:
       语句;
      break;
     default:
      break;
  }
 */

// 基本使用
// ctl + i: 自动代码格式化
let rating = "A" // 判定字符串
switch rating {
case "A", "a":
    print("Great!")
case "B", "b":
    print("Just so so!")
case "C", "c":
    print("It's not good")
default:
    print("No rating!")
}

// 和区间运算符的结合
var score = 93 // 整型
switch score {
case 90...100:
    print("Score is A!")
case 80...89:
    print("Score is B!")
case 70...79:
    print("Score is C!")
default:
    print("Score is not good")
}

// 需求: 判定二维坐标系的点, 是否是单元向量(1,0),(0, -1),(-1, 0), (0,1)
let vector = (1, 0)
switch vector {
case (0, 0):
    print("The point is origin!")
case (1, 0):
    print("It is the unit vector on the positive x-axis!")
case (-1, 0):
    print("It is the unit vector on the negative x-axis!")
case (0, 1):
    print("It is the unit vector on the positive y-axis!")
case (0, -1):
    print("It is the unit vector on the negative y-axis!")
default:
    print("It is the ordinary point.")
}

// 需求: 判定二维坐标系的点在x轴上(y=0), 还是y轴上(x=0)
let point2D = (10, 0)
switch point2D {
case (_, 0):
    print("It is on the x-axis!")
case (0, _):
    print("It is on the y-axis!")
case (-1...1, -1...1):
    print("It is near to the origin!")
default:
    print("It is ordinary point!")
}

// switch中的值绑定(value binding): 使用常量来接收元组分量的值
// 如果已经穷举所有case可能性, 不需要写default语句
switch point2D {
case (let x, 0):
    print("The x value is \(x)")
    // x的作用域仅在case内
case (0, let y):
    print("The y value is \(y)")
case (let x, let y):
    print("The point is (\(x), \(y))")
}

/* SQL语句: 有条件查询语句
 * select * from tableName where name="gaoyuanyuan"
 * 需求: 判定两位坐标系的点是否在两条直线上: y=x; y=-x
 */
switch point2D {
case let (x, y) where x == y:
    print("The point is on the line x==y!")
case let (x, y) where x == -y:
    print("The point is on the line x==-y!")
default:
    print("The point is ordinary point!")
    
}









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值