94

We can declare block as below in Objective-C.

typedef void (^CompletionBlock) (NSString* completionReason);

I'm trying to do this in swift, it give error.

func completionFunction(NSString* completionReason){ }
typealias CompletionBlock = completionFunction

Error : Use of undeclared 'completionFunction'

Definition :

var completion: CompletionBlock = { }

How to do this?

Update:

According to @jtbandes's answer, I can create closure with multiple arguments as like

typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()
Mani
  • 17,549
  • 13
  • 79
  • 100
  • 1
    @Downvotters: Please explain what is wrong with this question? – Mani Jun 10 '14 at 08:29
  • 1
    there are a number of people feels we should learn swift language first and then write. Foolish feelings... – Janak Nirmal Jun 11 '14 at 10:10
  • @Mani Hi, would you mind also showing how you would assign that type alias to a `var` (i.e., `var completion: CompletionBlock = {....}` using multiple arguments? Thanks. – Unheilig Apr 17 '15 at 08:14

2 Answers2

144

The syntax for function types is (in) -> out.

typealias CompletionBlock = (NSString?) -> Void
// or
typealias CompletionBlock = (result: NSData?, error: NSError?) -> Void
var completion: CompletionBlock = { reason in print(reason) }
var completion: CompletionBlock = { result, error in print(error) }

Note that the parentheses around the input type are only required as of Swift 3+.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • If it take more than two arguments, how can we do that? Would you please direct me to reference in that book or anyother? – Mani Jun 10 '14 at 06:00
  • Best book for Swift: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/ca/jEUH0.l – David Skrundz Jun 10 '14 at 06:02
  • @NSArray I know only one book is available for swift. But I'm asking about that corresponding chapter with topic... :) – Mani Jun 10 '14 at 06:05
  • 4
    @jtbandes It's working. I've created with two arguments as `typealias CompletionBlock = ( completionName : NSString, flag : Int) -> ()` – Mani Jun 10 '14 at 06:09
  • @zumzum It separates the parameter name "`reason`" from the method body "`println(reason)`" – jtbandes Jul 01 '14 at 17:35
14

Here is awesome blog about swift closure.

Here are some examples:

As a variable:

var closureName: (inputTypes) -> (outputType)

As an optional variable:

var closureName: ((inputTypes) -> (outputType))?

As a type alias:

typealias closureType = (inputTypes) -> (outputType)
BLC
  • 2,240
  • 25
  • 27