[Swift] I tried to implement exception handling for vending machines

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.

specification

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.

Implementation

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 \ type error process. Implement error handling using do-catch statements.

** 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.

スクリーンショット 2020-12-30 18.15.50.png

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.

スクリーンショット 2020-12-30 18.33.34.png

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.

スクリーンショット 2020-12-30 19.30.05.png

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

[Swift] I tried to implement exception handling for vending machines
[Swift] I tried to implement the function of the vending machine
[Swift] Correction of exception handling for vending machines (extra edition)
Swift beginners tried to implement vending machine logic!
I tried to implement the Iterator pattern
I tried to implement ModanShogi with Kinx
Swift beginners tried to implement microwave logic!
I tried to implement polymorphic related in Nogizaka.
I tried to implement deep learning in Java
I want to design a structured exception handling
I tried to implement a server using Netty
I tried to implement file upload with Spring MVC
I tried to implement TCP / IP + BIO with JAVA
I tried to implement Firebase push notification in Java
I tried to implement Stalin sort with Java Collector
[Java] I tried to implement Yahoo API product search
I tried to implement the Euclidean algorithm in Java
[Swift] I tried to implement Instagram profile-like UI with UICollectionView only with code without storyboard
I tried to implement the like function by asynchronous communication
I tried to introduce Bootstrap 4 to the Rails 6 app [for beginners]
[Rails] I tried to implement batch processing with Rake task
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
I tried to implement a buggy web application in Kotlin
I tried to verify yum-cron
[Rails] I tried to implement "Like function" using rails and js
I tried to implement Ajax processing of like function in Rails
I want to create a chat screen for the Swift chat app!
I tried to implement the image preview function with Rails / jQuery
I tried to implement flexible OR mapping with MyBatis Dynamic SQL
I tried to reimplement Ruby Float (arg, exception: true) with builtin
Swift: I want to chain arrays
I tried to chew C # (indexer)
I tried to summarize iOS 14 support
I tried to interact with Java
I tried to explain the method
[Swift 5] Implement UI for review function
[Rails] How to write exception handling?
I tried to summarize Java learning (1)
I tried to understand nil guard
[For Java beginners] About exception handling
I tried to summarize Java 8 now
I tried to chew C # (polymorphism: polymorphism)
I tried to explain Active Hash
[Rails] I tried to implement a transaction that combines multiple DB processes
[iOS] I tried to make a processing application like Instagram with Swift
I tried to summarize the methods used
I tried to introduce CircleCI 2.0 to Rails app
I tried using Realm with Swift UI
I tried migrating Processing to VS Code
I tried Cassandra's Object Mapper for Java
I tried to summarize Java lambda expressions
I tried to get started with WebAssembly
I tried to solve AOJ's Binary Search
[Swift] Easy to implement modal with PanModal
[Swift] How to implement the countdown function
[Swift5] How to implement standby screen using'PKHUD'
I tried to summarize the Stream API
I tried to build AdoptOpenjdk 11 on CentOS 7
What is Docker? I tried to summarize
I tried to build Ruby 3.0.0 from source
[Swift5] How to implement animation using "lottie-ios"