Chris
Chris

Reputation: 8020

Closure declaration in swift 2.0

In swift 2.0, what is the correct closure declaration? I've seen examples done like below, but it doesn't seem to work for me.

In SomeClass:

var successBlock: (Bool) -> () = { _ in }

and it would be called like this:

self.successBlock(true)

Then in SomeOtherClass:

let someClass = SomeClass
someClass.successBlock {
    success in
    //code here

}

Bit this gives me an error: (_) -> is not convertible to Bool

I've tried googling around a bit but with no luck... Is there a syntax change with swift 2.0 or is it me?

Upvotes: 0

Views: 166

Answers (1)

Kametrixom
Kametrixom

Reputation: 14973

If you're trying to set the successBlock, you should do it with an = sign:

someClass.successBlock = { success in
    // code here
}

EDIT: You mentioned that you only want your other class to "listen", but what does "listen" mean? If you want to listen to every time the closure gets called with some value and do something depending on it, you may want to have an array of closures instead:

var successBlocks : [Bool -> Void] = []

which you can invoke like this:

let value = true
successBlocks.forEach{ $0(value) }

When you want to listen to invocations, you can do this:

someClass.successBlocks.append( { success in
    // do the stuff
} )

which won't override any other closures already in the array, so probably that's what you wanted to do.

Upvotes: 2

Related Questions