-8

I'm new with Swift 2, I never had developed in Apple. Objective C has seemed ugly and you have to write a lot of code, so Swift liked because the syntax is similar to Java and C and here my question:

In Java you can define a class of this way:

new Thread(){
  public run(){
      // anything    
  }
}.start();

Then, Swift can do this? And how?

Thank and greetings


Solution

    let myThread=NSThread(target: self, selector: "backgroundWork", object: nil)
    myThread.start()

}

func backgroundWork(){

    for (self.counter=0;self.counter<10;self.counter++){
        //self.myLabel.text = String(self.counter) // Not update UI
        self.performSelectorOnMainThread( Selector("updateLabel"), withObject: nil, waitUntilDone: false )
        sleep(3)
    }

}

func updateLabel(){
    self.myLabel.text = String(self.counter)
}
pnuts
  • 58,317
  • 11
  • 87
  • 139
  • 2
    That's an anonymous class, which in Java 8 would be implemented using a lambda, and in Groovy and Swift would be implemented using a [Closure](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94) – Andreas Sep 28 '15 at 17:59
  • That is a initialization of a new Thread-Object and not the definition of a class. – Christian Sep 28 '15 at 17:59
  • @Christian It's the definition of a new anonymous class, subclassing `Thread`. – Andreas Sep 28 '15 at 18:00
  • Yes is anonymous class, thank Andreas. Solved. – sr.WhiteSkull Sep 29 '15 at 12:15
  • ...and thanks Objective-C programmers by negative votes ;) – sr.WhiteSkull Sep 29 '15 at 12:18

1 Answers1

0

Mostly this syntax (inline definition of anonymous classes) exists because Java doesn't allow the concept of closures or lambda functions, so if you want to pass a function to be invoked you have to pass an instance of a class with the function then declared inline.

In contrast, Swift, like most modern languages has a specific closure syntax which allows you to directly pass executable blocks to another routine, essentially it allows you to treat functions as first class language entities.

So, the bottom line is that no, Swift doesn't allow the construct you've asked about, but it does provide equivalent functionality for the dominant use case. The code most analogous to your example would be:

dispatch_async(...) {
    Code to be executed asynchronously here
}

Which is really just syntactic sugar for:

dispatch_async(..., {
    Your code here
})

Since the anonymous object is being created only as a holder for a single object, there's really no need for the object, or indeed, the class, and hence the syntax. The only time the Java syntax has a slight advantage is if the callee needs to maintain multiple related callbacks.

David Berry
  • 40,941
  • 12
  • 84
  • 95