Swift 笔记(四)
来源:互联网 发布:云计算怎么实现 编辑:程序博客网 时间:2024/05/21 06:47
我的主力博客:半亩方塘
Making Decisions
1、Consider this code:
let number = 10switch (number) {case let x where x % 2 == 0: print("Even")default: print("Odd")}
This will print the following:
Even
This switch statement uses the let-where syntax, meaning the case will match only when a certain condition is true. In this example, you've designed the case to match if the value is even-that is, if the value modulo 2 equals 0.
The method by which you can match values based on conditions is known as pattern matching.
2、Another way you can use switch
statements to great effect is as follows:
let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)switch (coordinates) {case (0, 0, 0): print("Origin")case (_, 0, 0): print("On the x-axis.")case (0, _, 0): print("On the y-axis.")case (0, 0, _): print("On the z-axis.") default: print("Somewhere in space")}
You're using the underscore to mean that you don't care about the value. If you don't want to ignore the value, then you can use it in your switch
statement, like this:
let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)switch (coordinates) {case (0, 0, 0): print("Origin")case (let x, 0, 0): print("On the x-axis at x = \(x)")case (0, let y, 0): print("On the y-axis at y = \(y)")case (0, 0, let z): print("On the z-axis at z = \(z)")case (let x, let y, let z): print("Somewhere in space at x = \(x), y = \(y), z = \(z)") }
let-where
syntax you saw earlier to match more complex cases. For example:let coordinates: (x: Int, y: Int, z: Int) = (3, 2, 5)switch(coordinates) {case (let x, let y, _) where y == x: print("Along the y = x line.")case (let x, let y, _) where y == x * x: print("Along the y = x^2 line.")default: break}
0 0
- Swift 笔记(四)
- 学习Swift笔记 (四)
- swift学习笔记(四)
- 基础知识—Swift学习笔记(四)
- Swift语言基础笔记(四)
- Swift语言学习笔记(四)
- swift 学习笔记四
- Swift 笔记四:collection集合
- Swift学习笔记(四)函数
- 自学Swift(四)
- swift(四)
- swift UITableView(四)
- Swift 数据类型(四)
- Swift 笔记 (四) —— 集合类型
- 老猫swift学习笔记(四):函数
- Swift 語言入門(四)標準函式
- swift 学习记录(四)
- Swift基础(四)数组
- jq与JS点击显示隐藏二级菜单的几种方法
- 白话Spring(基础篇)---helloworld
- 1090 Higest Price in Supply Chain
- 学习android service记录
- Linux 初始化之 Systemd机制简介
- Swift 笔记(四)
- UML图与机房收费系统实例
- 使用Memory Analyzer tool(MAT)分析内存泄漏(二)
- java.lang.ThreadLocal实现原理和源码分析
- 四叉树空间索引原理及其实现
- ios 开发中 动态库 与静态库的区别
- LA-3942 (字典树模板)
- ES2015系列(三) 正则表达式
- 大型网站架构系列:20本技术书籍推荐