//: Playground - noun: a place where people can play
import UIKit
/*
* 本节内容:
* 1.guard else
*/
/*
* 基本使用伪代码:
var x = 9
guard x > 10 else {
// 不能满足上面的条件(不能保证条件)
return
}
// 满足条件, 业务逻辑
*/
// 基本使用
func guardFuncExample(age: Int) {
guard age <= 40 else {
print("不符合报考研究生的年龄条件!")
return
}
// 如果符合条件(age <= 40)
print("符合报考年龄")
}
// 和可选型结合
// if let解包是文档中Optional Binding(可选型绑定)
// if var解包 / guard let解包
func guardFuncOptional(str: String?) {
// guard let解包
// if let newStr = str { }
guard let newStr = str else {
// str可选型为nil
print("str is nil")
return
}
// str可选型不为nil
print("newStr is \(newStr)")
}
// 适用场景
// 需求: 用兜里的钱, 买商品(钱数>=价格); 拿一个包, 装买的商品(容量>=体积)
func buySomething(money: Int, price: Int, capacity: Int, volume: Int) {
// 使用if/else
if money >= price {
print("\(money - price) Yuan left.")
if capacity >= volume {
print("I can buy it!")
print("\(capacity - volume) cubic meters left.")
} else {
print("Not enough capacity!")
}
} else {
print("Not enough money!")
}
}
/*
* 优势:
* 1.guard没有嵌套, 整齐
* 2.语义性非常明确
*/
func buySomethingWithGuard(money: Int, price: Int, capacity: Int, volume: Int) {
// 使用guard
guard money >= price else {
print("Not enough money!")
return
}
// 钱够的
guard capacity >= volume else {
print("Not enough capacity")
return
}
// 钱也够, 容量也够
print("I can buy it!")
print("\(money - price) Yuan left.")
print("\(capacity - volume) cubic meters left.")
}
/*
* 懒加载:
@property (noatomic) NSMutableArray *mutableArray;
- (NSMutableArray *)mutableArray {
if (_mutableArray == nil) {
_mutableArray = [[NSMutableArray alloc] init];
}
return _mutableArray;
}
// 另一种懒加载
- (NSMutableArray *)mutableArray {
if (_mutableArray != nil) {
return _mutableArray;
}
_mutableArray = [[NSMutableArray alloc] init];
// 一堆代码
}
*/
Swift 系统学习 17 guard else (守护)
最新推荐文章于 2023-07-07 00:04:09 发布