简体   繁体   中英

How to fix escaping closure? Error is: Converting non-escaping value may allow it to escape

Here is my code:

class Main {
    init() {
        let x = Sub(s: foo)
    }

    func foo(completion: @escaping (String?)->Void) {
        DispatchQueue.global().async {
            completion(nil)
        }
    }
}

class Sub {
    var s: ((String?)->Void)->Void
    init(s: @escaping ((String?)->Void)->Void) {
        self.s = s
    }
}

I get error here let x = Sub(s: foo)

Converting non-escaping value to '(String?) -> Void' may allow it to escape`

I have added all the escapes that XCode prompted me to add, but the error is still there. What do I need to do to fix this?

You need another layer of @escaping :

class Sub {
    var s: (@escaping (String?) -> Void) -> Void

    init(s: @escaping (@escaping (String?) -> Void) -> Void) {
        self.s = s
    }
}

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