zuaaef
zuaaef

Reputation: 31

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?

Upvotes: 2

Views: 1007

Answers (1)

dan
dan

Reputation: 9825

You need another layer of @escaping:

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

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

Upvotes: 5

Related Questions