Use unity "seconds" in Swift

Hi,


I have one question how to use the unity "seconds" in a Swift Playground.

I coded a countdown and want to make it as an countdown for 30 seconds.

The source code is quiet easy:


var countdown = 30
var start = 1
func countdown_running(value: Int) {
    while start <= value {
        print(start)
        if start == 30 {
            print("Finished")
        }
        start += 1
    }
}


What I have to submit for counting seconds?

Thank you for your help!

Accepted Reply

Then Playgrounds is the right place to post. But it's not a big issue, moderator of the forums will move this thread if he/she thinks it's needed.


I do not understand what you mean with `unity`, but when you want to implement sort of countdown timer, you use `Timer`.


In the Xcode Playground, you can write something like this.

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

var countdown = 30
var start = 1

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    if start <= countdown {
        print(start)
        start += 1
    } else {
        print("Finished")
        timer.invalidate()
    }
}


Seems it's a countup timer.

Replies

You mean Swift Playground on iPad, not Xcode Playground on mac?

(Just for confirmation, the code needed may not be much different.)

No, I want to create a Xcode Playground on Mac.

Then Playgrounds is the right place to post. But it's not a big issue, moderator of the forums will move this thread if he/she thinks it's needed.


I do not understand what you mean with `unity`, but when you want to implement sort of countdown timer, you use `Timer`.


In the Xcode Playground, you can write something like this.

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

var countdown = 30
var start = 1

let timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
    if start <= countdown {
        print(start)
        start += 1
    } else {
        print("Finished")
        timer.invalidate()
    }
}


Seems it's a countup timer.

Thank you! It works!

Sorry for the language and understanding mistake - I'm new in App Development and the Community and of course, you see, English is not my mother ******...

But thanks for you feedback - I try to improve it all the time :-)!