1

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)
Community
  • 1
  • 1
HelloToYou
  • 335
  • 5
  • 14

3 Answers3

0

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)
}
Alessandro Ornano
  • 34,887
  • 11
  • 106
  • 133
0

self refers to the object for which a method (a function defined within a class) is defined, so can only be used in a method. (It is the equivalent of this in C++/Java/Javascript.) In your code, sayHello() is a global function, not a method, so there is no self to refer to.

In order for the scheduledTimerWithTimeInterval() function call to work with those arguments, it must be called within an instance method so that there is a self, and that class must have a method named sayHello().

You could also change the target: to another object as long as that object has a sayHello() method.

Paul Richter
  • 6,154
  • 2
  • 20
  • 22
0

Basically an asynchronous timer doesn't work in a Playground and a since the top level of a Playground isn't a class there is no self property.

To test NSTimer in a Playground

  • Wrap the timer in a class.
  • Import XCPlaygound.
  • Add XCPlaygroundPage.currentPage.needsIndefiniteExecution = true to enable support of asynchronous tasks.
vadian
  • 274,689
  • 30
  • 353
  • 361