Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating threads in swift?

I am trying to spawn a thread in swift. So I have this line:

. . .

let thread = NSThread(target: self, selector: doSomething(), object: nil)

. . .

doSomething is a function within the scope of the class.

That line gives this error: "could not find an overload for init() that accepts the supplied arguments"

What am I missing here? Ho can I create a new thread in swift?

like image 790
zumzum Avatar asked Jul 02 '14 21:07

zumzum


2 Answers

As of Xcode 7.3 and Swift 2.2, you can use the special form #selector(...) where Objective-C would use @selector(...):

let thread = NSThread(target:self, selector:#selector(doSomething), object:nil)
like image 107
rob mayoff Avatar answered Nov 09 '22 08:11

rob mayoff


NSThread takes a selector as it's second parameter. You can describe Objective-C selectors as Strings in Swift like this:

let thread = NSThread(target: myObj, selector: "mySelector", object: nil)

Swift functions aren't equivalent objective-c methods though. If you have a method in a swift class, you can use it as a selector if you use the @objc attribute on the class:

@objc class myClass{
    func myFunc(){
    }
}

var myObj = myClass()
let thread = NSThread(target: myObj, selector: "myFunc", object: nil)
like image 34
Connor Avatar answered Nov 09 '22 07:11

Connor