theUturn
theUturn

Reputation: 1131

swift how to create completion handler for this function

I am new to swift please suggest me how to create completion handler for this service function

func postRequest(router: Router, postData: [String: String], completion: @escaping (Result<Int, Error>) -> ()) { ......

I am stuck here

ServiceLayer.postRequest(router: Router.register, postData: postData) { (<#Result<Int, Error>#>) in
            return ....
        }

Upvotes: 1

Views: 1410

Answers (4)

Samps
Samps

Reputation: 1049

There are already couple of correct answers. If you have 2 similar post functions with different callback. F.e

func postRequest(router: Router, postData: [String: String], completion: @escaping (Result<Int, Error>) -> Void) {}
func postRequest(router: Router, postData: [String: String], completion: @escaping (Error) -> Void) {}

Then you can specify the type in call like that:

ServiceLayer.postRequest(router: Router.register, postData: postData) { (result: Result<Int, Error>) in
}

ServiceLayer.postRequest(router: Router.register, postData: postData) { (error: Error) in
}

Upvotes: 0

Dilan
Dilan

Reputation: 2698

ServiceLayer.postRequest(router: Router.register, postData: postData) { (response) in
            switch response{
                 case .success(let id):
                     print(id)
                     //do something with return id
                 case .failure(let error):
                    //error handle
            }
        }

more info Result type tutorial

Upvotes: 0

emrcftci
emrcftci

Reputation: 3514

Result has .success and .failure cases so you can use this Result like ->

postRequest(router: Router.register, postData: postData) { result in
    switch result {
    case .success(let value): 
        // Do something

    case .failure(let error): 
        // Do something
    }
}

BONUS

Understanding Result Type in Swift 5

Upvotes: 1

Rob C
Rob C

Reputation: 5073

It's just asking you to give the closure argument a name. You can do this:

ServiceLayer.postRequest(router: Router.register, postData: postData) { result in
}

Upvotes: 1

Related Questions