zoukankan      html  css  js  c++  java
  • swif-throws异常抛出

    import UIKit
    
    enum VendingMachineError: Error {
        case invalidSelection //选择无效
        case insufficientFunds(coinsNeeded: Int) //金额不足
        case outOfStock //缺货
        
    }
    
    struct Item {
        var price: Int
        var count: Int
    }
    
    class VendingMachine {
        var inventory = [
            "Candy Bar": Item(price: 12, count: 7),
            "Chips": Item(price: 10, count: 4),
            "Pretzels": Item(price: 7, count: 11)
        ]
        //货币沉淀
        var coinsDeposited = 0
        func dispenseSnack(snack: String) {
            print("Dispensing (snack)")
        }
        func vend(itemNamed name: String) throws {
            guard let item = inventory[name] else {
                throw VendingMachineError.invalidSelection
            }
            guard item.count > 0 else {
                throw VendingMachineError.outOfStock
            }
            guard item.price <= coinsDeposited else {
                throw VendingMachineError.insufficientFunds(coinsNeeded: item.price - coinsDeposited)
            }
            coinsDeposited -= item.price
            var newItem = item
            newItem.count -= 1
            inventory[name] = newItem
            print("Dispensing (name)")
        }
    }
    
    
    class First_Demo3: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            self.navigationItem.title = "throws异常抛出"
            self.view.backgroundColor = UIColor.white
            
            
            let vend = VendingMachine()
            //货币沉淀
            vend.coinsDeposited = 5
    
            /*
             try抓取异常,如果执行成功,那么执行 vend.vend(itemNamed: "Pretzels")。cathch 完枚举的三个错误以后,要把catch关闭,即:
    注意:最后加入一个空的catch,否则则会报错 Error throw from are not handled because the enclosing catch is not exhaustive  意思就是catch没有关闭。
             */
            
            do {
                try  vend.vend(itemNamed: "Pretzels")
                // 没有错误抛出
            }catch VendingMachineError.invalidSelection{
                print("选择无效")
                // 有错误抛出
            }catch VendingMachineError.outOfStock{
                print("缺货")
            }catch VendingMachineError.insufficientFunds(let coinsNeeded){
                print("还差(coinsNeeded)货币")
            }catch {
                
            }
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
        
    }
    
     
  • 相关阅读:
    文件内容排名算法,输入排名函数,返回排名后的文件名
    线段树做大数据排序
    给字符排序-基类排序二分查找-JavaScript
    后缀数组、名次数组-JavaScript
    二分查找法、二分去重排序法,返回最接近的位置和实际位置
    用四叉树对图像分类,获取tag和key
    Linux显示所在Git分支
    Linux中设置Git显示颜色
    屏蔽网页广告
    tf.add_to_collection,tf.get_collection简介
  • 原文地址:https://www.cnblogs.com/sayimba/p/6237235.html
Copyright © 2011-2022 走看看