Search code examples
swiftnstimer

Repeat function using NSTimer fails with target: self in Swift


I found this question and tried to copy the code to my Xcode project, but I'm getting the following error message.

error: use of unresolved identifier 'self'

What's the right way?

EDIT: Here the code, tested in a playground:

    //: Playground - noun: a place where people can play

import Cocoa
import Foundation

func sayHello() {
    print("hello World")
}

var SwiftTimer = NSTimer()
SwiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)

Solution

  • Usually using uppercase to the properties name it's considered as a bad attitude, you should use swiftTimer.

    These expressions are not allowed ad the top level:

    var swiftTimer = NSTimer()
    swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
    

    You must put it in a function like for example:

    override func viewDidLoad() {
            super.viewDidLoad()
            var swiftTimer = NSTimer()
            swiftTimer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("sayHello"), userInfo: nil, repeats: true)
    }