Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create function with two closures as params in Swift?

I need to translate such a func from Objective-C to Swift language. But can't find an example and can't get how to send 2 closures into func in Swift.

For example, original function in Objective-C:

- (void)getForDemoDataWithToken:(Token *)token
onSuccess:(void(^)(NSArray *demoData))success
onFailure:(void(^)(NSError *error))failure {
}

I know to send 1 closure as param:

getForDemoDataWithToken(token) {(success: String) -> Void in

// some code here

print(success)

}

But, how to send two closures?

Thank you

like image 311
Bogdan Laukhin Avatar asked Dec 24 '22 11:12

Bogdan Laukhin


1 Answers

What about this?

Declaration

func getForDemoDataWithToken(
    token: Token,
    onSuccess: (demoData:NSArray?) -> (),
    onFailure: (error:NSError?) -> ()) {

}

Invocation

getForDemoDataWithToken(Token(),
    onSuccess: { (demoData) -> () in

    },
    onFailure: { (demoData) -> () in

    }
)

A more Swifty approach

I usually see Swift code where only one closure is used. So instead of 2 distinct onSuccess and onFailure closures you could have just completion.

Next we should remember that NSArray is compatible with Swift but it's not the Swiftest way to use an array.

Let's see an example where the 2 concepts above are applied.

func getForDemoData(token:Token, completion:(data:[Foo]?, error:NSError?) -> ()) {

}

You can invoke it with the trailing closure syntax.

getForDemoData(Token()) { (data, error) -> () in
    if let data = data where error == nil {
        // success!
    } else {
        // oh no... something wrong here
    }
}
like image 179
Luca Angeletti Avatar answered Mar 18 '23 11:03

Luca Angeletti