J. Doe
J. Doe

Reputation: 13103

Calling closure inside closure

This is my code:

var work: ((Int, completionHandler: (() -> ()) -> ()))?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    work(1, {
        // Does not work.
    })

    workAsMethod(amount: 1) {
        // Works.
    }

    work = { (amount, completionHandler) in
        // Does not work
        completionHandler()
    }

    return true
}

func workAsMethod(amount: Int, completionHandler: @escaping (() -> ())) {
    // Works
    completionHandler()
}

When I am using a method with a block that I can call to indicate work is done, it works. When I try to do the same thing within a closure (closure inside closure), I can not get it to work.

What is the correct syntax to call a closure inside a closure to notify the 'listener' that the work is done?

Upvotes: 0

Views: 897

Answers (1)

vacawama
vacawama

Reputation: 154711

The type of your work closure needed work:

var work: ((Int, _ completionHandler: () -> ()) -> ())?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

    // Use optional chaining here to unwrap work before calling
    work?(1, {
        // This now works.
    })

    workAsMethod(amount: 1) {
        // Works.
    }

    work = { (amount, completionHandler) in
        // This now works
        completionHandler()
    }

    return true
}

func workAsMethod(amount: Int, completionHandler: @escaping (() -> ())) {
    // Works
    completionHandler()
}

work is an optional closure that takes an Int and a () -> () and it returns nothing -> ().

If you break down your type for work, your completionHandler has type (() -> ()) -> () which means your completionHandler takes a () -> () closure and returns nothing. You want your completerHandler to take no parameters. Because of the misplaced ( and ), your work was actually an optional tuple and not a closure type.

Upvotes: 2

Related Questions