Search code examples
swiftblock

How to define block in Swift like in Objective-C?


In ObjectiveC i can define block which will be used many places like

typedef void (^APISuccessHandler)(RKObjectRequestOperation *operation, RKMappingResult *result);

and then use it in (for example) ViewController propery

@property (nonatomic, copy) APISuccessHandler successHandler;

How do same in swift?


Solution

  • Use typealias

    typealias MyType=(str:String,num:Int)->()
    

    Then,

    var test:MyType = {(str,num) in
        println(str)
        println(num)
    }
    

    Execute the block

      test(str: "123", num: 1)
    

    Output

    123
    1