代码片段

import UIKit
import Foundation
import Darwin

// Swift的do-try-catch错误处理模式
enum ErrorType : Error
{
    case invalidProduct
    // 第二个枚举成员,表示缺少钱币而无法购买产品,同时显示缺少金钱的数额
    case insufficientCoins(coinsNeeded: Int)
    case outOfStock
}

struct Product
{
    var price: Int
    var count: Int
}

var totalCoins = 20

class Shop
{
    // 给类添加一个数组属性,表示该商店拥有的商品种类、价格和数量
    var products =
    [
        "Pudding": Product(price: 12, count: 7),
        "Donut": Product(price: 10, count: 4),
        "Cheesepuff": Product(price: 7, count: 11)
    ]
    
    func sell(productName:String) throws
    {
        guard let product = products[productName] else
        {
            throw ErrorType.invalidProduct
        }
        guard product.count > 0 else
        {
            throw ErrorType.outOfStock
        }
        guard product.price <= totalCoins else
        {
            throw ErrorType.insufficientCoins(coinsNeeded: product.price - totalCoins)
        }
        
        // 当以上异常均未发生时,即可正常进行交易。从硬币总数之中,减去需要购买的商品的价格
        totalCoins -= product.price
        
        var newItem = product
        newItem.count -= 1
        // 然后同步更新产品数组中的,当前被购买的商品的属性信息
        products[productName] = newItem
        print(">\(productName)")
    }
}

var shop = Shop()
 
do {
    // 用try语句,尝试购买指定名称的商品,因为商店中没有销售指定的产品,所以输出了非法商品的错误信息。
//    try shop.sell(productName: "Apple")
    try shop.sell(productName: "Pudding")
    
} catch ErrorType.invalidProduct {
    print("Invalid product.")
} catch ErrorType.outOfStock {
    print("Out Of Stock.")
} catch ErrorType.insufficientCoins(let coisNeeded) {
    print("Need \(coisNeeded) coins.")
}

代码截图

iShot20220408 下午10.17.38.png

Q.E.D.