bluenowhere
bluenowhere

Reputation: 2733

Calling self-defined closure in Swift

In objective-c I could define my own block type:

typedef void (^myBlock)(id param1, id param2, BOOL param3);

then define the block body somewhere else(e.g. another class) to do something with passed values like:

myBlock block = ^(id param1, id param2, BOOL param3) { 
 if (param3){
   NSLog("parameters:%@,%@",param1,param2)
 }};

To do the same thing in Swift I defined my block using typealias:

typealias myBlock = (param1:AnyObject, param2:AnyObject, param3:Bool) -> ()

but I couldn't simply call it like:

let block: myBlock = {param1,param2,param3 in 
 if (param3){
     print(param1,param2)
 }}

and there was a warning:

Initialization of immutable value 'block' was never used; consider replacing with assignment to '_' or removing it.

How can I call myBlock and define it's body in Swift?

Thanks in advance!

Upvotes: 0

Views: 67

Answers (2)

JulianM
JulianM

Reputation: 2550

There isn't anything wrong with your declaration. But as the word tells you, you are just declaring something and not calling. So the closure is not called anywhere.

Try this one

typealias myBlock = (param1:AnyObject, param2:AnyObject, param3:Bool) -> ()

let block: myBlock = {(param1,param2,param3) in 
 if (param3){
     print(param1,param2)
 }}

block(param1: 1,param2: 2,param3: true)

You have to replace the actual parameter with your values of course. Works like a charm as you can see in the playground screenshot.

enter image description here

Upvotes: 0

Alex
Alex

Reputation: 616

I think the warning appears because you didn't use "block" variable anywhere in your code.

After declared "block" variable, try to use it somewhere in your code.

Upvotes: 1

Related Questions