SwiftUI

SwiftUI #4: Intro to Timers

January 8, 2021
Stiff Torpid, the slowest man on Earth, has just fled the country.
Stiff Torpid, the slowest man on Earth, has just fled the country. (Drawing credit: my sister.)

On our journey to understanding the SwiftUI framework, we will be solving some problems in the great and splendid Mangoville, a small town that doesn’t have access to Xcode. I already got tons of requests from Mangopolitans!

I have terrible news… Stiff Torpid, the slowest man on Earth, has just fled the country. I guess he was tired of people making fun of how he slow is. Apparently, people mocking him made him sad, but motivated him to train and get faster. 

How do I know? He left a diary written in Slow, the slowest language ever. After hours and hours, historians from all around the world (interested in discovering a new language) finally decoded this language. The translated version of his diary says:

Wednesday, January 1st, 2020

My name is Stiff Torpid. I’m the slowest man alive. Three slow days ago, I decided to make hot chocolate for Iris. I lit up the fire, put the pot filled with milk there, and right when I thought everything was just fine, I accidently spilled the burning milk on my arm. It was really painful so I went to the doctor to see if it was that bad. He told me it looked fine, but when he heard how it happened, he burst out laughing. It really frightened me because he had a wet piece of lettuce stuck between his teeth, but it also gave me a wake-up call. In fact, I have planned to go train my speed somewhere in Antarctica.

Thursday, January 2nd, 2020

On my way to Antarctica. I hope I’ll make it in time.

(By the way, if you didn’t get that reference, then you’re clearly not a fan of Flash. No worries, I forgive you and will gladly explain the reference that this smart Stiff decided to add in his great diary. Iris is the name of Flash’s girlfriend and “My name is…man alive” is what Flash always says in the comics when there’s an issue.)

Anyway, the scientists think that if he’s going to train, he might need a timer. They also told Iris, Stiff’s girlfriend, and the Torpid family that everything will be just fine. We absolutely need to build him a timer app and fast! Let’s get going.

First, begin by making a new app by clicking on File > New > Project. Now, we’ll build our timer.

Start by adding these two variables at the beginning of your struct:

let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()    

@State var timeLeft = 10

The timer constant creates our timer and the timeLeft variable makes sure our countdown actually counts down.

Now, time to add a Text view (in the body) so that Stiff can see how much time is left:

Text("\(timeLeft)")

Great! We’re almost done. We now need to add this code, which takes care of subtracting seconds whenever the timer isn’t done:

.onReceive(timer) {  _ in
    if self.timeLeft > 0 {          
        self.timeLeft -= 1       
    }            
}

Now we must not forget to make a button for Stiff to restart his training. Since he wants to be really fast, we will set the countdown to be 10 seconds long:

Button(action: { 
    self.timeLeft = 10            
}) {
    Text(“Restart”)           
}

Good. Now that we’re done, just check that your code looks like this and that your app looks like the GIF below:

import SwiftUI

struct ContentView: View {
    let timer = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect()
    @State var timeLeft = 10
    
    var body: some View {
        VStack {
            Text("\(timeLeft)")
                .onReceive(timer) { _ in
                    if self.timeLeft > 0 {
                        self.timeLeft -= 1
                    }
                }

            Button(action: {
                self.timeLeft = 10
            }) {
                Text("Restart")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Wow! I just read this in today’s newspaper:

AN ANONYMOUS PERSON HELPS THE SLOWEST MAN ON PLANET EARTH SPEAK ENGLISH FOR THE FIRST TIME!

A team of scientists have found Mr. Torpid a bit lost. He ended up outside a restaurant, which was 11 minutes on foot from his house… Anyways, some wonderful person made a wonderful app to help him. Stiff was jubilant to see that and said, “Thaaaaaaaaaaaaaaaaaaaaaaaank… youuuuuuuuuuuuuuuuuuuuuuuuu!!!!!!” It’s incredible, isn’t it?!? Stiff spoke actual English for the first time in his entire life! Thank you, anonymous person!

Yay! I’m glad Stiff is happy again! 

If you want to test out the final result, you can download the project from my GitHub page here.

You Might Also Like

No Comments

Leave a Reply