Import UIKitenumVendingmachineerror:error { CaseInvalidselection//invalid selection CaseInsufficientfunds (Coinsneeded:int)//Insufficient Amount CaseOutofstock//Out of stock }structItem {var price:int var count:int}classVendingmachine {var inventory= [ "Candy Bar": Item (Price: A, Count:7), "Chips": Item (Price:Ten, Count:4), "Pretzels": Item (Price:7, Count: One) ] //Currency precipitationvar coinsdeposited =0func Dispensesnack (snack:string) {print ("dispensing \ (snack)")} func vend (Itemnamed name:string) throws {Guard Let item= Inventory[name]Else { ThrowVendingmachineerror.invalidselection} guard Item.count>0 Else { ThrowVendingmachineerror.outofstock} guard Item.price<= coinsdepositedElse { ThrowVendingmachineerror.insufficientfunds (CoinsNeeded:item.price-coinsdeposited)} Coinsdeposited-=item.price var newitem=Item Newitem.count-=1Inventory[name]=newitem Print ("dispensing \ (name)") }}classFirst_demo3:uiviewcontroller {Overridefunc viewdidload () {super.viewdidload () Self.navigationItem.title="throws exception throws"Self.view.backgroundColor=Uicolor.white Let Vend=Vendingmachine ()//Currency precipitationvend.coinsdeposited =5 /*try to fetch the exception, if execution succeeds, then execute Vend.vend (itemnamed: "Pretzels"). Cathch after the enumeration of three errors, to close the catch, that is: note: Finally add an empty catch, otherwise it will error error throw from was not handled because the enclosing catch was not Exhaustive means that the catch is not closed. */ Do { TryVend.vend (itemnamed:"Pretzels") //no error thrown}Catchvendingmachineerror.invalidselection{Print ("invalid selection") //There are errors thrown}Catchvendingmachineerror.outofstock{Print ("Out of stock") }Catchvendingmachineerror.insufficientfunds (Let coinsneeded) {print ("still poor \ (coinsneeded) currency") }Catch { } } Overridefunc didreceivememorywarning () {super.didreceivememorywarning ()//Dispose of any resources the can be recreated. } }
Swif-throws exception throws