Swift 系统学习 17 guard else (守护)

//: 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];
    // 一堆代码
 }
 */




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值