This article is a continuation of [Swift] I tried to implement the function of the vending machine. If you haven't seen it, please take a look.
The GitHub repository will be ** here **.
Now, I would like to implement the following exception handling.
I would like to list the specifications in a bulleted list when implementing it. ** ・ You cannot put more than your money into the vending machine. ・ Items that exceed the amount cannot be purchased ・ You cannot buy items that are out of stock **
For the time being, I will add the above three.
Now, let's implement the very first "You can't put in more money than you have".
As the processing content,
If possessed money> input amount
, it is processed that it can be input.
Since it is a synchronous process, it may be an optional \
** This time, there are two choices, whether you have enough money or not, so we will implement it with the former error handling. ** **
Changed the sendMoneyAction ()
method as follows.
Added -> String?
To define a return type that allows nil.
First of all, when the method is executed, We are checking the magnitude relationship between the argument value (input amount) and the money property (possession amount).
** If a value greater than the money property is passed at this point, You shouldn't be able to put money in a vending machine. ** **
So, if the value is larger, we are doing return nil
.
ViewController.swift
func sendMoneyAction(value: Int) -> String? {
if money < value {
return nil
}
money -= value
inputMoney += value
moneyLabel.text = "Possession:\(money)Circle"
inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
return "\(value)I put a circle."
}
Next is the processing of the caller.
(Since the process is the same after case 2:
, it is omitted.)
With guard let result = sendMoneyAction (value: 10) else {}
I'm checking if the returned value is nil.
If it is nil, execute inside {}, otherwise execute print (result)
.
ViewController.swift
@IBAction func sendMoney(_ sender: Any) {
guard let button = sender as? UIButton else {
return
}
switch button.tag {
case 1:
guard let result = sendMoneyAction(value: 10) else {
print("I don't have enough money.")
return
}
print(result)
default: return
}
}
The actual behavior looks like the image.
Now I want to commit once and implement the next exception handling feature!
The next function to be implemented is ** "You cannot purchase products that exceed the price" **. Exception handling will be performed when you press the purchase button for a product that is more expensive than the current amount.
It's easy to handle, from the inputMoney property (the amount currently in) If the value after subtracting the purchase amount is 0 or more, there is no problem with purchasing.
So, add if inputMoney --100 <0 {}
and you're done.
ViewController.swift
//Purchase process
func buyDrink(product: Drink) {
switch product {
case .irohasu:
if inputMoney - 100 < 0 {
print("I don't have enough money.")
return
}
inputMoney -= 100
inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
print("I bought I Lohas.")
}
}
The actual behavior is as shown in the image.
I put in 200 yen and bought tea in the afternoon and the balance is 50 yen. If you try to buy I Lohas in this state, ** "Not enough money" ** will be output.
Finally, I would like to implement ** "I can't buy items that are out of stock" **.
We have newly defined a property that holds the stock of each product. (I thought it would have been better to define it as a structure instead of an enumeration ...)
We have also defined a inventoryControl ()
method to manage inventory.
This method checks if it is in stock and returns false if it does not exist If it exists, it decrements the inventory by one and returns true.
And in the buyDrink ()
method that performs the purchase process,
First of all, check if it is in stock with the inventoryControl ()
method.
After that, check if the fee is enough, If neither condition is met, the process is performed to the end.
There are two types of errors: "out of stock" and "not enough money". ** So I think it would have been better to use a do-catch statement that can display detailed errors. ** **
I was able to implement the function for the time being, so I decided to clear the mission ... However, I'm curious, so I wish I could post a proper one in the next article.
ViewController.swift
var irohasuStock = 3
var ryokuchaStock = 2
var gogothiStock = 1
//Purchase process
func buyDrink(product: Drink) {
switch product {
case .irohasu:
if !inventoryControl(product: product) {
print("no stock.")
return
}
if inputMoney - 100 < 0 {
print("I don't have enough money.")
return
}
inputMoney -= 100
inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
print("I bought I Lohas.")
}
}
//Inventory control
func inventoryControl(product: Drink) -> Bool {
switch product {
case .irohasu:
if irohasuStock == 0 {
return false
}
irohasuStock -= 1
return true
}
}
The actual behavior is as follows.
Put in 500 yen and buy 2 green teas in stock.
Then when I try to buy green tea again, It is displayed that it is out of stock and cannot be purchased.
With the above, I would like to complete the sample implementation of the vending machine.
** In the next article, I will fix the error part I made earlier. ** ** I hope you can see that as well.
Click here for the next article -> [Swift] Fixed exception handling for vending machines (extra edition)
Thank you for watching until the end.
Recommended Posts