Duck
Duck

Reputation: 36003

Is there a way to run a closure without testing it?

I use this scheme constantly in my classes

typealias nullHandle = ()->Void
var runOnLoad: nullHandle?

So, when I create an instance of that class I do...

let object = MyClass()
object.runOnLoad = { ()->Void in
  // do something
}

Inside the class, I always have to do this before running that closure:

if self.runOnLoad != nil {
  self.runOnLoad()!
}     

because I cannot guarantee that runOnLoad is not nil and if I try to run a nil runOnLoad it will crash.

I am new to swift after programming in Objective-C for a century. I am using this pattern in swift because this is what I would do in Objective-C.

Is there a better way to do this whole thing in Swift?

thanks

Upvotes: 2

Views: 42

Answers (1)

Martin R
Martin R

Reputation: 539965

Optional chaining works with closures as well:

self.runOnLoad?()

executes the closure if it is not nil, and does nothing otherwise.

Of course you can also test the closure, but that is better done with optional binding instead of forced unwrapping:

if let runOnLoad = self.runOnLoad {
    runOnLoad()
}

Upvotes: 5

Related Questions