Search code examples
swiftnstimer

NSTimer Swift difficulty


I am trying to create a NSTimer so that I can move a UIImageView down but The NSTImer is having difficulty, saying first that this.

var timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target:self(), selector: Selector ("mrockdown"), userInfo: nil, repeats: true)

is missing argument for parameter #1 in call. But when I remove the brackets from the target:self() it tells me

Cannot invoke 'scheduledTimerWIthTimerInterval' with an argument list of type '(Double, target: ViewController -> () -> ViewController, selector: Selector, userinfo: nil, repeates Bool.

What should I do?


Solution

  • The problem has to do with where you are saying this. It looks like you are trying to say this as part of a property declaration:

    class ViewController {
        var timer = ...
        // ...
    }
    

    But you can't do that, because there is no self as far as a stored property is concerned. You need to declare the timer as an Optional and then initialize it later:

    class ViewController {
        var timer = NSTimer!
        func someMethod {
            timer = ...
        }
    }
    

    Then you will remove the parentheses (they are wrong) and everything will compile just fine.