Weird: let statement leads to nil

I have not touched Swift code for more than a year. My skills become rusty.

I am not sure what stupid errors I made in the following code:

extension Bundle {
    func readResourceFile(_ filename: String) -> String? {
        if let fileUrl = self.resourceURL?.appendingPathComponent(filename, isDirectory: false) {
            return try? String(contentsOf: fileUrl)
        }
        return nil
    }
}

class MyVC {
    //...
    @IBAction func testButton_click(_ sender: Any) {
        Task.init { await self.test1() }
    }

    func test1() async {
        var loaded = false

        do {
            let result = try await self.webView.evaluateJavaScript("typeof(jQuery)")
            loaded = result as? String == "function"
        } catch {
            self.statusLabel.stringValue = "error: \(error)"
        }

        if (loaded) {
            await self.runUserScript(self.input.string)
            return
        }

        let scriptFiles = ["jQuery.js", "Scriptlets.js"]
        var count = 0

        for scriptFile in scriptFiles {
            print("Loading \(scriptFile)")
            do {
                if let script = Bundle.main.readResourceFile(scriptFile) {
                    try await self.webView.evaluateJavaScript(script)
                    print("Loaded \(scriptFile)")
                    count += 1
                }
            } catch {
                self.statusLabel.stringValue = "error: \(error)"
            }
        }
    }

The line if let script = Bundle.main.readResourceFile(scriptFile) { succeeds but script still is nil and causes app crash in next line self.webView.evaluateJavaScript(script).

Bundle.main.readResourceFile(scriptFile) is working if I run this line elsewhere.

EDIT: When I click on the I button in debugging on variable script I get: (String) script = <no location, value may have been optimized out>

However, I can print(script) and the output is correct.

The error is:

2023-04-28 17:53:20.523568+0800 WKWebViewTest[21469:545345] :0: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value

It seems self.webView.evaluateJavaScript cannot be called within async context:

//Task.init
 {
            //await self.test1()
            //try? await 
                self.webView.evaluateJavaScript("alert('test')")
}

The above simple code runs without any problem in synchronous mode, but will cause a runtime exception if is called in Task.init block. Is this by design? But I don't believe it.

Weird: let statement leads to nil
 
 
Q