当前位置:网站首页>Swift Error Handling
Swift Error Handling
2022-07-03 12:34:00 【iWillook】
//
// main.swift
// Ultimate
//
// Created by Mewlan Musajan on 3/20/21.
//
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
init(deposite: Int) {
coinsDeposited = deposite
}
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)")
if coinsDeposited != 0 {
print("Returing extra \(coinsDeposited) BTC")
}
}
}
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)
}
try buyFavoriteSnack(person: "Eve", vendingMachine: VendingMachine(deposite: 12))
struct PurchasedSnack {
let name: String
init(name: String, vendingMachine: VendingMachine) throws {
try vendingMachine.vend(itemNamed: name)
self.name = name
}
}
print("\(try PurchasedSnack(name: "Candy Bar", vendingMachine: VendingMachine(deposite: 12)).name) was vended")
var vendingMachine = VendingMachine(deposite: 8)
do {
try buyFavoriteSnack(person: "Alice", vendingMachine: vendingMachine)
print("Success! Yum.")
} catch VendingMachineError.invalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.outOfStock {
print("Out of Stock.")
} catch VendingMachineError.insufficientFunds(let coinsNeeded) {
print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
} catch {
print("Unexpected error: \(error).")
}
func nourish(with item: String) throws {
do {
try vendingMachine.vend(itemNamed: item)
} catch is VendingMachineError {
print("Couldn't buy that from the vending machine.")
}
}
do {
try nourish(with: "Beet-Flavored Chips")
} catch {
print("Unexpected non-vending-machine-realted error: \(error)")
}
边栏推荐
- 剑指Offer03. 数组中重复的数字【简单】
- Itext7 uses iexternalsignature container for signature and signature verification
- 2.8 overview of ViewModel knowledge
- 1-2 project technology selection and structure
- Flutter 退出登录二次确认怎么做才更优雅?
- Is it OK to open an account for online stock speculation? Is the fund safe?
- Atomic atomic operation
- Integer int compare size
- Use Tencent cloud IOT platform to connect custom esp8266 IOT devices (realized by Tencent continuous control switch)
- Shutter widget: centerslice attribute
猜你喜欢
剑指Offer07. 重建二叉树
C language improvement article (wchar_t) character type
剑指Offer04. 二维数组中的查找【中等】
Sword finger offer09 Implementing queues with two stacks
Shutter widget: centerslice attribute
Flutter 退出登录二次确认怎么做才更优雅?
剑指Offer05. 替换空格
(construction notes) ADT and OOP
【ArcGIS自定义脚本工具】矢量文件生成扩大矩形面要素
2021 autumn Information Security Experiment 1 (password and hiding technology)
随机推荐
Sword finger offer05 Replace spaces
Bert running error: attributeerror: module'tensorflow contrib. tpu' has no attribute 'InputPipelineConfig'
JVM内存模型
Fluent: Engine Architecture
Use Tencent cloud IOT platform to connect custom esp8266 IOT devices (realized by Tencent continuous control switch)
ES6 standard
公纵号发送提示信息(用户微服务--消息微服务)
4000 word super detailed pointer
Flutter: self study system
Airflow installation jump pit
Official website of Unicode query
Summary of error prone knowledge points: Calculation of define s (x) 3*x*x+1.
347. Top k high frequency elements
2021 autumn Information Security Experiment 1 (password and hiding technology)
Idea packages the web project into a war package and deploys it to the server to run
2.6 preliminary cognition of synergetic couroutines
【嵌入式】---- 内存四区介绍
Shutter widget: centerslice attribute
【ArcGIS自定义脚本工具】矢量文件生成扩大矩形面要素
lambda与匿名内部类的区别