holger
holger

Reputation: 331

How to create closure with specific typealias in swift?

I'm using the swift package OnboardKit and it requires a specific closure type that I cannot figure out. The class OnboardPage requires a type OnboardPageAction for the parameter action.

public typealias OnboardPageCompletion = ((_ success: Bool, _ error: Error?) -> Void)
public typealias OnboardPageAction = (@escaping OnboardPageCompletion) -> Void
OnboardPage(title: "Title",
            description: "description",
            action: action)

This is my latest attempt, I tried several variations along those lines.

let action: ((_ success: Bool, _ error: Error?) -> ()) = {_,_ in
    print("help")
}

XCode fails with the error message:

Cannot convert value of type '(Bool, Error?) -> Void' to expected argument type 'OnboardPageAction?' (aka 'Optional<(@escaping (Bool, Optional) -> ()) -> ()>')

What am I doing wrong here? Is the mistake in my closure definition or in the way I use it in the OnboardPage() call? Thanks :)

(I learned details about closures here Closures Swift How To, but I am not able to define the right closure type that the package expects)

Upvotes: 3

Views: 572

Answers (2)

LuLuGaGa
LuLuGaGa

Reputation: 14398

The declaration of an action should look like this to match the defintions provided:

let action: OnboardPageAction = { (_ closure: ((_ success: Bool, _ error: Error?) -> Void)) in
    print("action")
}

Upvotes: 1

Sweeper
Sweeper

Reputation: 272750

Judging from the context, I guess that the purpose of the action parameter is to allow you run some code when an OnboardPage is presented. This "action" might take some time (it might not finish when action returns), so it gives you a completion handler parameter that you can call to indicate that what you want to do is done.

If you just want to print Hello, you can just call the parameter after you printed hello to indicate that you finished what you want to do:

OnboardPage(title: "Title",
        description: "description",
        action: { completion in
            print("Hello")
            completion(true, nil)
        })

or simply

OnboardPage(title: "Title",
        description: "description") {
            print("Hello")
            $0(true, nil)
        }

The first argument indicates whether the action is successful, the second contains an optional error for when it fails.

Upvotes: 1

Related Questions