swift : Closure declaration as like block declaration

后端 未结 2 507
南笙
南笙 2020-12-04 08:13

We can declare block as below in Objective-C.

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

I\'m trying to do this in swift

相关标签:
2条回答
  • 2020-12-04 08:55

    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)
    
    0 讨论(0)
  • 2020-12-04 08:57

    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+.

    0 讨论(0)
提交回复
热议问题