Create an optional block as a variable

I have a simple class where I declare a block as a variable:

class MyObject : NSObject { var progressBlock:(progress:Double) -> ()? init() { } } 

As far as I understand, if it is defined in this way, progressBlock does not need to be initialized in the initializer init()

However, when I try to compile, I get its error:

 Property 'self.progressBlock' not initialized at super.init 

So the question is, how do I create an optional progressBlock , so I am not getting this error?

+8
ios swift objective-c-blocks optional
source share
2 answers

As you wrote it, the compiler assumes that progressBlock is a closure that returns an optional empty tuple instead of an optional closure that returns an empty tuple. Try writing it like this:

 class MyObject:NSObject { var progressBlock:((progress:Double) -> ())? init() { progressBlock = nil progressBlock = { (Double) -> () in /* code */ } } } 
+24
source share

Adding connor to the answer. An additional block can be written as:

 var block : (() -> ())? = nil 

Or as an explicit Optional :

 var block : Optional<() -> ()> = nil 

Or better yet, with a custom type

 typealias BlockType = () -> () var block : BlockType? = nil 
+3
source share

All Articles