[Swift] I tried to implement the function of the vending machine

As for me, I have a contract with mentor Yamataku. Among them, there was the issue of trying to build business logic as applied learning.

As one of the subjects, There was a vending machine logic, so I'll try to create it!

For those who are motivated, it is better to contract with a mentor than a programming school It's cheap and I think it's efficient, so I highly recommend it!

** Search for "Swift Mentor" **!

Before creating logic

I used to write code without thinking about anything, I was taught to do it in order, so I would like to define it exactly as it is!

I also learned about GitHub the other day. I would like to continue practicing there as well.

Link to GitHub in the following order? Did. I will leave it as a memorandum.

  1. Create a repository on GitHub
  2. Create a project with XCode
  1. Run the git remote add origin repository URL (https: // ~) in your terminal
  2. Do Commit or Push from Source Controll of XCode

I feel that it was made in this order.

If you can't, once from the terminal after 3. If you run git push -u origin main, you may be able to register or something.

The GitHub repository for this project will be ** here **.

specification

First, consider the logic specifications of this vending machine. ・ Initial money of 1000 yen ・ The amount that can be invested is 10 yen, 50 yen, 100 yen, 500 yen, and 1000 yen. ・ The target products are "I Lohas", "Green Tea", and "Afternoon Tea". ・ Details of the product are as follows

I Lohas Green Tea Afternoon tea
Amount of money 100 yen 120 yen 150 yen
stock 3 pieces 2 pieces 1 piece

・ Purchase is cash only ・ After purchasing the product, reduce the amount notation. ・ If you press the change button, you will get a refund.

For the time being, I would like to go with specifications like this!

By the way, either Playground or Storyboard is acceptable, so This time I would like to implement it in Storyboard.

I will implement

First of all, I will implement the UI as it is appropriate. This time it will be a considerably deteriorated version of a real vending machine ... (laughs)

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

How about something like this for the time being!

"Purchase", "10 yen to 1000 yen", and "change" are implemented by UIButton (). Other than that, it is implemented by UILabel ().

Next, we will work with Storyboard and the code.

** If you code each button separately, the amount will increase, so I tried to summarize the related buttons. ** **

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

So, once you commit to GitHub I would like to make a backup and then write the actual code.

I feel like there was a git reset command, so if you want to go back, you should be able to go back. (I don't know if this usage is recommended ...)

Then, I would like to write the process from here.

As for the order of implementation, I would like to implement in the order of actual purchase.

I think I'll put the money first, so If you press the button with each amount listed, your money will decrease, I would like to write a code that will increase the amount of money invested.

This time, each amount button is grouped into one sendMoney () method. So, ** Check which button was pressed and then perform the appropriate processing. ** **

First, select the target button on the Storyboard and set the value for tag. This time, I started from 10 yen with tag1, tag2, tag3, tag4, tag5.

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

After that, conditional branching occurs depending on which tag is selected in the switch statement.

The value is entered in the argument sender, ** Since it is Any type, it is cast to UIButton type at the guard-let part. ** **

ViewController.swift


    //Input amount selection button
    @IBAction func sendMoney(_ sender: Any) {
        guard let button = sender as? UIButton else {
            return
        }
        
        switch button.tag {
        case 1:
            print("1")
        case 2:
            print("2")
        case 3:
            print("3")
        case 4:
            print("4")
        case 5:
            print("5")
        default: return
        }
    }

At this point, it became possible to identify which button was pressed, so I would like to define a method that reflects the amount of money.

The functions implemented by the methods to be defined are ** A function to subtract the amount of money you put in from your money and a function to increase the value of the amount. ** **

I have defined two new properties and defined a method to update their values.

In the sendMoneyAction () method, the value of the pressed button is received as an argument. We are updating each label by subtracting the value from the possession money and adding the input amount to the amount.

ViewController.swift



    var money = 1000
    var inputMoney = 0

    //Input amount selection button
    @IBAction func sendMoney(_ sender: Any) {
        guard let button = sender as? UIButton else {
            return
        }
        
        switch button.tag {
        case 1:
            sendMoneyAction(value: 10)
        case 2:
            sendMoneyAction(value: 50)
        case 3:
            sendMoneyAction(value: 100)
        case 4:
            sendMoneyAction(value: 500)
        case 5:
            sendMoneyAction(value: 1000)
        default: return
        }
    }

    func sendMoneyAction(value: Int) {
        money -= value
        inputMoney += value
        
        moneyLabel.text = "Possession:\(money)Circle"
        inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
    }

When you actually press the 50 yen button and the 100 yen button You can see that the amount of money you have is 850 yen and the amount is 150 yen.

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

Since I implemented one function, I once ** commit ** to GitHub and Next, I think that I will buy a drink if I put in money, so I will implement a purchase button.

This is also identified by the tag as before. The code will be similar, so I won't explain it!

** When you press the purchase button on the left, 100 yen will be deducted from the amount. ** ** I thought I would use the code, but in reality I think that the products will be sorted. The purchase button on the left is not always 100 yen.

So when you press each purchase button I decided to specify a product name and perform processing suitable for that product name.

** By doing so, maintenance against fluctuations in price and changes in product position can be performed. Is it a little easier? I think. ** **

To do so, we first defined an enum and defined a case for each product.

When you press the purchase button, the buyDrink () method that performs the purchase process is executed.

The argument specifies the case of enumerated Drink. Pattern matching is performed with a switch statement and processing suitable for that case is performed.

ViewController.swift



enum Drink {
    case irohasu
    case ryokucha
    case gogothi
}

    //Buy button
    @IBAction func buyButton(_ sender: Any) {
        guard let button = sender as? UIButton else {
            return
        }
        
        switch button.tag {
        case 1:
            buyDrink(product: .irohasu)
        case 2:
            buyDrink(product: .ryokucha)
        case 3:
            buyDrink(product: .gogothi)
        default:
            return
        }
    }

    //Purchase process
    func buyDrink(product: Drink) {
        switch product {
        case .irohasu:
            inputMoney -= 100
            inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
            print("I bought I Lohas.")
        case .ryokucha:
            inputMoney -= 120
            inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
            print("I bought green tea.")
        case .gogothi:
            inputMoney -= 150
            inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
            print("I bought tea in the afternoon.")
        }
    }

The following is the result of purchasing afternoon tea and green tea after actually putting in 500 yen. You can see that the amount has decreased and the purchase result is output to the log.

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

It's getting pretty much like that! Finally, we will implement a function ** that will be refunded when the change button is pressed when the amount of money left is **.

I thought, but before that, I will commit to GitHub. As development progresses, I almost forget to commit (laughs)

The function of the change button is extremely simple, just add the rest of the amount to your money. It's a little lonely if it's just that, so I'll add a process to output to the log as well.

ViewController.swift



    //Change button
    @IBAction func changeButton(_ sender: Any) {
        money += inputMoney
        print("\(inputMoney)I got a yen change")
        inputMoney = 0
        moneyLabel.text = "Possession:\(money)Circle"
        inputMoneyLabel.text = "Amount of money:\(inputMoney)Circle"
    }

That's it.

After putting in 500 yen, I bought a 150 yen afternoon tea and The behavior when you receive a change of 350 yen is as shown in the image.

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

I think that there is no problem because the money I have is 850 yen and it is output firmly in the log!

This completes the minimum vending machine logic.

It makes sense to say the minimum ** This code does not describe any exception handling. ** **

For example, you can tap 1000 yen many times to make your money negative. You can also purchase the product with the price of 0 yen. Besides, it is a code full of holes, such as buying many even though the stock is fixed in the specifications.

So, in the next article, I would like to implement it firmly here and there.

The next article will be here. -> [Swift] I implemented exception handling for vending machines

Thank you for watching until the end.

Recommended Posts

[Swift] I tried to implement the function of the vending machine
Swift beginners tried to implement vending machine logic!
I tried to implement the like function by asynchronous communication
[Swift] How to implement the countdown function
I tried to implement the Iterator pattern
I tried to implement Ajax processing of like function in Rails
I tried to implement the image preview function with Rails / jQuery
[Swift] How to implement the LINE login function
[swift5] How to implement the Twitter share function
[Swift] How to implement the fade-in / out function
I tried using the Server Push function of Servlet 4.0
I tried to summarize the state transition of docker
05. I tried to stub the source of Spring Boot
I tried to reduce the capacity of Spring Boot
I tried to implement the Euclidean algorithm in Java
I tried to implement a function equivalent to Felica Lite with HCE-F of Android
I tried to summarize the basics of kotlin and java
I tried to explain the method
I tried to summarize the basic grammar of Ruby briefly
I tried to build the environment of WSL2 + Docker + VSCode
[Rails] I tried to implement "Like function" using rails and js
I tried to solve the Ruby karaoke machine problem (there is an example of the answer)
[For Swift beginners] I tried to summarize the messy layout cycle of ViewController and View
I tried to develop the cache function of Application Container Cloud Service in the local environment
I tried to solve the problem of "multi-stage selection" with Ruby
I tried to build the environment of PlantUML Server with Docker
[Swift] How to implement the Twitter login function using Firebase UI ①
I tried using the cache function of Application Container Cloud Service
I tried to check the operation of gRPC server with grpcurl
I tried to summarize the methods of Java String and StringBuilder
[Swift] How to implement the Twitter login function using Firebase UI ②
I tried to solve the problem of Google Tech Dev Guide
I tried to summarize the methods used
I tried to summarize the Stream API
I tried to implement ModanShogi with Kinx
Swift beginners tried to implement microwave logic!
[Spring Boot] I investigated how to implement post-processing of the received request.
I tried to summarize the key points of gRPC design and development
I tried to make full use of the CPU core in Ruby
I tried to visualize the access of Lambda → Athena with AWS X-Ray
[Swift] I investigated the variable expansion "\ ()" that realizes the mysterious function of Swift UI.
I tried to measure and compare the speed of GraalVM with JMH
How to implement the email authentication function at the time of user registration
I want to output the day of the week
I tried to implement polymorphic related in Nogizaka.
[Rails] I tried to raise the Rails version from 5.0 to 5.2
I tried to organize the session in Rails
I tried to chew C # (basic of encapsulation)
I tried to implement deep learning in Java
I want to var_dump the contents of the intent
How to implement the breadcrumb function using gretel
[For beginners] How to implement the delete function
I tried to set tomcat to run the Servlet.
I tried to implement a server using Netty
[Swift] Termination of the program by the fatalError function
I tried using the profiler of IntelliJ IDEA
Rails API mode I tried to implement the keyword multiple search function using arrays and iterative processing.
What I tried when I wanted to get all the fields of a bean
I tried to compare the infrastructure technology of engineers these days with cooking.
[Beginner] I tried to decorate the bar after displaying the details of the hamburger menu
I tried to implement file upload with Spring MVC