【LearnSwift】异常处理

源码下载

下载地址

源码

import UIKit

class ViewController: UIViewController {
    
    enum VendingMachineError : ErrorType {
        
        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("dispensine \(snack)")
        }
        
        func vend(itemNamed name:String) throws {
            
            guard var 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
            
            --item.count
            
            inventory[name] = item
            
            dispenseSnack(name)
        }
    }
    
    let favoriteSnacks = [
    
        "Alice" : "Chips",
        
        "Bob"   : "Licorice",
        
        "Eve"   : "Pretzels"
    ]
    
    func buyFavoriteSnack(person:String, vendingMachine:VendingMachine) throws {
    
        let snackName = favoriteSnacks[person] ?? "Candy Bar"
        
        try vendingMachine.vend(itemNamed: snackName)
    }
    
    func someThrowingFunction(value : Int) throws -> Int {
    
        // ...
        
        return value*3
    }
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        let vendingMachine = VendingMachine()
        
        vendingMachine.coinsDeposited = 8
        
        // 标准用法
        do {
        
            try buyFavoriteSnack("Alice", vendingMachine: vendingMachine)
            
        } catch VendingMachineError.InvalidSelection {
        
            print("Invalid Selection.")
            
        } catch VendingMachineError.OutOfStock {
        
            print("Out of Stock.")
            
        } catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
        
            print("Insufficient funds.Please insert an addtional \(coinsNeeded) coins.")
            
        } catch is ErrorType {
        
            print("其他异常.")
        }
        
        // try?
        let x = try? someThrowingFunction(100)
        
        // 相当于
        let y :Int?
        
        do {
        
            y = try someThrowingFunction(100)
            
        } catch {
        
            y = nil
        }
        
        // TODO: try!
        
        // TODO: defer 关键字
        
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,885评论 25 709
  • 第一部分 插件的介绍 Google 在2013年5月的I/O开发者大会推出了基于IntelliJ IDEA Jav...
    Jannonx阅读 2,342评论 0 13
  • 清晨站在田野间 雨露滋润着稻田 辛勤耕耘秋丰收 老牛在前人在后
    hwc阅读 297评论 0 0
  • 山顶的城堡, 灰色的墙,青色的瓦。 山顶的城堡, 蓝天下,银光摇。 虫鸣鸟叫尽在你膝下。 城堡里,你微笑, 闪电都...
    H3190阅读 277评论 0 0
  • 错误:-bash: /usr/local/bin/pod: /System/Library/Frameworks/...
    清风拂松阅读 141评论 0 0