-1

I am trying to build a metronome app, where when activated the app flashes a light and plays a sound in given intervals. However, I don't know where to put a while loop, as putting it inside the viewcontroller prompts an "expected declaration" error. The idea is just for something like:

while metronome_is_on = true {
    //code that plays sound/flashes light with given delayed intervals
}

So, where can I run this loop in the app? Or is there a better practice for this?

  • 1
    Use a Timer perhaps? – Joakim Danielson Aug 21 '20 at 19:42
  • 1
    A `while` loop to wait for something is bad practice. **Don't ask, tell**. A better practice is to notify when the metronome stops. – vadian Aug 21 '20 at 19:43
  • Almost anything is a better practice. For instance you might make the metronome's state (on or off) observable, so that any other object can get an event when the state changes. And if the object is to something happen every interval, the metronome should give off a notification or other observable signal. – matt Aug 21 '20 at 19:49

1 Answers1

0

As I understand, you probably are new to Swift, so here it goes...

All of your code setup, goes inside the ViewController's viewDidLoad. viewDidLoad is called the moment a ViewController is loaded into memory.

To play a sound, check here; How to play a sound using Swift?

To run a block of code on certain intervals, check here; https://www.hackingwithswift.com/articles/117/the-ultimate-guide-to-timer

As far your while-loop is concerned, have in mind that to check for equality you need ==. = is used for value assignment.

Sotiris Kaniras
  • 520
  • 1
  • 12
  • 30
  • 1
    If you're using `Timer` for playing the ticks and flashing a light, then you could set the `Timer`'s interval to `60.0 / bpm` where `bpm` is the beats per minute that your metronome is set to. A `UISlider` might be a good way to set the bpm for the metronome. Wikipedia says bpm values typically vary from `40` to `208`. – vacawama Aug 21 '20 at 20:56