Call a static method from NSTimer. Is it possible?

Is it allowed to call a static method from NSTimer? The compiler will not allow this, complaining about the cryptic "Extra argument" in the call.

struct MyStruct { static func startTimer() { NSTimer.scheduledTimerWithTimeInterval(1.0, target: MyStruct.self, selector: "doStuff", userInfo: nil, repeats: true) } static func doStuff() { println("Doin' it.") } } MyStruct.startTimer() 

But of course, this works great ...

 class MyClass { func startTimer() { NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true) } func doStuff() { println("Doin' it.") } } var instanceOfClass = MyClass() instanceOfClass.startTimer() 

Am I just using the syntax wrong, or is this not allowed?

+6
source share
1 answer

NSTimer uses the Objective-C environment to dynamically call methods. When a struct declared, you use the Swift runtime, so NSTimer collaboration NSTimer not possible. Structures are different from classes, and you can learn more about them here .

In addition, the static function is equivalent to the class method in Objective-C, so if this was your original goal, the following should suffice:

 class MyClass: NSObject { class func startTimer() { NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "doStuff", userInfo: nil, repeats: true) } class func doStuff() { println("Doin' it.") } } MyClass.startTimer() 
+3
source

Source: https://habr.com/ru/post/984337/


All Articles