Mysterious "will never be executed" warning

this is a misleading diagnostic due to top level code generally behaving oddly in some cases. if you wrap everything in a do {} block or function, you'll see that the problem is that the closure captures a variable before it's declared:

<source>:53:54: error: closure captures 'data' before it is declared [capture_before_declaration]
51 | 
52 | do {
53 | let workItem = DispatchWorkItem(qos: .userInitiated) {
   |                                                      `- error: closure captures 'data' before it is declared [capture_before_declaration]
54 |     let result = workfunc()
55 |     print(result)
56 | }
57 | 
58 | let data : Data? = {
   |     `- note: captured value declared here [captured_value_declared_here]
59 |     let baseURL = URL.currentDirectory()
60 |     guard let matfileURL = URL(string: "filename.bin", relativeTo: baseURL)
   :
74 | func workfunc() -> Int {
75 |     /* Do something */
76 |     if let data = data {
   |                   `- note: captured here [value_captured_here]
77 |         print("File found. \(data)")
78 |         /* Additionally do something else */
Compiler returned: 1

i'm fairly sure there are existing issues and threads on this matter, though they elude me at the moment...


edit: here's a thread and corresponding issue i recall from not too long ago. and another related thread comment from further in the past.

4 Likes