美文网首页iOS开发学习
Swift的do-try-catch错误处理模式

Swift的do-try-catch错误处理模式

作者: 香橙柚子 | 来源:发表于2021-01-17 02:16 被阅读0次
    
    import UIKit
    
    enum ErrorType: Error{
        case invalidProduct  //没有指定产品
        case lackCoin(coinsLack: Int)  //缺少钱币
        case understock //存货不足
    }
    
    struct Product {  //商品
        var price: Int
        var count: Int
    }
    var totalCoins = 20  //金币总数
    
    class Shop {
        var products =
            [
                "milk": Product(price: 12, count: 7),
                "bread": Product(price: 10, count: 4),
                "cookies": Product(price: 2, count: 5)
            ]
        
        func sell(productName: String) throws {
            guard let product = products[productName] else {
                throw ErrorType.invalidProduct
            }
            guard product.count > 0 else {
                throw ErrorType.understock
            }
            guard product.price <= totalCoins else {
                throw ErrorType.lackCoin(coinsLack: product.price - totalCoins)
            }
            
            totalCoins -= product.price
            var productCurrent = product
            productCurrent.count -= 1
            products[productName] = productCurrent
            
            print("我卖了一个\(productName)")
            
        }
    }
    
    class ViewController: UIViewController {
    
        var shop = Shop()
        
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view.
            
            do {
            // try shop.sell(productName: "wew")
                try shop.sell(productName: "milk")
                try shop.sell(productName: "milk")
            } catch ErrorType.invalidProduct {
                print("无效商品")
            } catch ErrorType.lackCoin(let coin) {
                print("还缺少\(coin)个金币")
            } catch ErrorType.understock {
                print("存货不足")
            } catch {
                print("未知错误")
            }
             
            print("哈哈哈,还可以继续执行")
        }
    
    }
    

    相关文章

      网友评论

        本文标题:Swift的do-try-catch错误处理模式

        本文链接:https://www.haomeiwen.com/subject/owtaaktx.html