Swift 错误处理/访问权限

enum ErrorType: Error {
    case invalidType
    case outOfStack
    case needMoreCoins(count: Int)
}

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

class SaleMachine {
    //定义商品类型
    var itemType = [
        "Chocolote" : Item(price: 8, count: 6),
        "bread" : Item(price: 5, count: 7),
        "Chips" : Item(price: 6, count: 4)
    ]
    
    //定义投币数量
    var coinsDeposited = 0
    
    //购买函数
    func buySomeThings(itemName: String) throws {
        
        defer {
            print("退出清理") //不管有没有错误抛出 都会调用。   相当于finally。
        }
        
        print("开始售卖")
        guard let item = itemType[itemName] else {
            throw ErrorType.invalidType
        }
        
        guard item.count > 0 else {
            throw ErrorType.outOfStack
        }
        
        guard coinsDeposited >= item.price else {
            throw ErrorType.needMoreCoins(count: item.price - coinsDeposited)
        }
        
        //正常售卖操作
        coinsDeposited -= item.price
        
        var newItem = item
        newItem.count -= 1
        itemType[itemName] = newItem
        
        print("售卖成功")
    }
}


var machine = SaleMachine()
machine.coinsDeposited = 3

do {
    try machine.buySomeThings(itemName: "bread")
} catch ErrorType.invalidType {
    print("no such things")
} catch ErrorType.outOfStack {
    print("out of stack")
} catch ErrorType.needMoreCoins(let needCoins) {
    print("need more coins:\(needCoins)")
} catch {
    print("没有预想到的错误, 兜底用的")
}
/**
 open: 允许其他模块访问、继承、复写。  只有类类型才可以用open, 结构体等不可以用open修饰,用public
 public: x允许其他模块访问,但是不能继承、复写
 internal: 默认的类型,模块内部可以访问
 private: 私有的。   扩展extension 在同一个文件里 可以访问private类里的属性
 fileprivate: 文件内私有, 本文件内使用。
 */

你可能感兴趣的:(Swift 错误处理/访问权限)