How to create typealias for completion handlers with named arguments
Asked Answered
B

2

6

What I have so far is this:

  1. I've defined typealias completion handler

    typealias UserCompletionHandler = (_ object: User?, _ error: ApiError?) -> Void
    
  2. And I've created a service function that is using this typealias

    func login(email: String, password: String, completion: UserCompletionHandler) {
       // ...
       // this part here handles API call and parsing logic
       // ...
    
       completion(user, nil)
    }
    

What I want to achieve is to have more readable completion callback with parameters by introducing named arguments. Idea is to end up with this:

   completion(object: user, error: nil)

Or even better to make error parameter optional, so I can just call

   completion(object: user)

Issue is that I can't find a way to change typealias definition to achieve this.

Braided answered 6/4, 2021 at 13:55 Comment(0)
B
4

Apparently this is not possible. You can find the explanation behind this choice in the swift evolution proposal: 0111-remove-arg-label-type-significance.md

Function types may only be defined in terms of the types of the formal parameters and the return value. Writing out a function type containing argument labels will be prohibited

Brume answered 6/4, 2021 at 14:22 Comment(0)
Y
3

Not sure if this answer is ideal, but you could use a tuple as your input argument:

typealias UserCompletionHandler = ((object: User?, error: ApiError?)) -> Void

and the usage would look like this:

completion((object: user, error: nil))
Yoshida answered 6/4, 2021 at 15:39 Comment(1)
I like this approach. It does have extra braces around it, but it does give cleaner naming and improves readability of the handler usage. Thanks Edward!Braided

© 2022 - 2024 — McMap. All rights reserved.