if let / guard / switch
2015-12-02 00:00
309 查看
摘要: if let / guard / switch
/// if let
/// guard - 是和 if let 刚好相反的指令
/// Swift 2.0 推出的语法
// switch
1. 不需要 break
2. 不在局限在 对 int 的分支,可以对任意数据类型进行检测
3. 各个 case 之间,不会穿透,如果有多个值,使用 , 分隔
4. 定义变量,不需要使用 {} 分隔作用域
5. 在 swift 中,必须涵盖所有条件,每一个 case 至少包含一条语句
/// if let
func demo1() { let oName: String? = "张三" let oAge: Int? = 20 if oName != nil && oAge != nil { print("Mr" + oName! + "---" + String(oAge!)) } // if let 可以设置数值,进入分支后,name 可以保证一定有值 if let name = oName { print("Hi " + name) } // 多值的设置,使用 , 分隔 // 注意:if let 语句中不能使用 && || 条件 if let name = oName, age = oAge { print("Hi " + name + "---" + String(age)) } }
/// guard - 是和 if let 刚好相反的指令
/// Swift 2.0 推出的语法
func demo2() { let oName: String? = "张三" let oAge: Int? = 20 guard let name = oName else { print("name 为 nil") return } guard let age = oAge else { print("age 为 nil") return } // 代码执行到此,name 和 age 一定有值 // 在实际开发中,复杂的代码在条件判断之后 // 使用 guard 会让嵌套层次少一层! print("Hi \(name) --- \(age)") }
// switch
1. 不需要 break
2. 不在局限在 对 int 的分支,可以对任意数据类型进行检测
3. 各个 case 之间,不会穿透,如果有多个值,使用 , 分隔
4. 定义变量,不需要使用 {} 分隔作用域
5. 在 swift 中,必须涵盖所有条件,每一个 case 至少包含一条语句
func switchDemo() { let number = "11" switch number { case "10", "11": let name = "老王" print("\(name) 好") case "9": print("良") default: break } }
相关文章推荐
- PHP8新特性之match表达式
- cmd if条件 条件判断
- 三个有用的 Switch 命令
- 详解Lua中的if语句的使用方法
- perl 控制结构 条件控制 if while
- C++条件语句和条件运算符的使用方法讲解
- VC++的if语句应用范围分析
- Zend Guard使用指南及问题处理
- Thinkphp模板标签if和eq的区别和比较实例分析
- javascript if条件判断方法小结
- js 中的switch表达式使用示例
- 基于C中含有if的宏定义详解
- Linux SHELL if命令参数说明
- bat批处理 if 命令示例详解
- PHP代码保护--Zend Guard的使用详解
- 由php if 想到的些问题
- Nginx实现if多重判断配置方法示例
- (C和指针) #if 0/#if 1...#end if
- C#中if语句使用概述
- ASP中if语句、select 、while循环的使用方法