简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM