简体   繁体   中英

Passing non-escaping closure to function expecting an @escaping closure

How can I solve the issue of passing non-escaping closure to function expecting an @escaping closure, with this limitation that I cannot make the function non-escaping.

Here is my codes and the issue:

func function1(string: @escaping (() -> String) -> Void) {

    string({ "Hello, world!" })

}

func function2(value: @escaping () -> String) {  // I cannot remove @escaping here, because the function needs it to work!

    print(value())

    // some more codes ...

}

func function3() {

    function1(string: { stringValue in

        function2(value: stringValue)         // issue is here!

    })
}

Add @escaping to the inner function:

func function1(string: @escaping (@escaping () -> String) -> Void) {
    string({ "Hello, world!" })
}
func function2(value: @escaping () -> String) { 
    print(value())
}
func function3() {
    function1(string: { stringValue in
        function2(value: stringValue)
    })
}

(Part of the problem here is that you have given your parameters really bad names, so that you confuse yourself about what's what.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM