Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Jialong Zhang
Jialong Zhang
9,821 Points

I want to execute a function after certain seconds, but not working with the code below"

Why does value is always 0? if statement or perhaps while statement is not working with DispatchQueue

import UIKit

var value = 0

func add(){
    value += 1
    print("new value: \(value)")
}

if value < 21 {
    DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute:{
        add()
    })
    print("new value: \(value)")
}

1 Answer

Magnus Hållberg
Magnus Hållberg
17,232 Points

First of all I'm pretty sure you will have to format the "now()" result since it will hold date and time, otherwise it wont know what you are referring to when you want to add 1 to it. Also I cant see how the "value" variable will change unless you use your if statement in a loop or function, now its just an if statement that will run one time and at this point wont trigger the add function that will add 1 to value. That is why value is always 0, it newer changes.