Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 defined this way, progressBlock does not have to be initialized in the init() initializer

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

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

So the question is, how do I create an optional progressBlock, so I don't get this error?

like image 543
zumzum Avatar asked Jul 28 '14 21:07

zumzum


2 Answers

The way you have written it, the compiler assumes 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 instead:

class MyObject:NSObject {
    var progressBlock:((progress:Double) -> ())?
    init() {
        progressBlock = nil
        progressBlock = { (Double) -> () in /* code */ }
    }
}
like image 160
Connor Avatar answered Nov 14 '22 23:11

Connor


Adding to connor's reply. An optional 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
like image 21
Can Avatar answered Nov 15 '22 00:11

Can