Why "if" must add before "let" on method of adding webview?

    if let htmlFile = NSBundle.mainBundle().pathForResource("BullsEye", ofType: "html") {
    
        if let htmlData = NSData(contentsOfFile: htmlFile) {
    
     let baseURL = NSURL(fileURLWithPath: NSBundle.mainBundle().bundlePath)
    
      webView.loadData(htmlData, MIMEType: "text/html", textEncodingName: "UTF-8", baseURL: baseURL)
     }

I tried out to remove that “if” before “let” but error was reported at “let htmlData = NSData(contentsOfFile: htmlFile)”. please help on why “if” must be used herein? Any solution to get the same functionality above however no “if” was used?

In the statement let htmlData = NSData(contentsOfFile: htmlFile), htmlData is inferred to be of type NSData?. NSData(contentsOfFile:) is a failable initialiser; it’s not guaranteed to return a value, and can return nil.

If you think that, given your particular htmlFile, it is guaranteed, then you can apply the ! operator to force-unwrap that optional. So if you code let htmlData = NSData(contentsOfFile: htmlFile)!, htmlData will be inferred to be of type NSData instead of NSData? - but your app will crash if NSData(contentsOfFile:) ever does fail.

if let is a safety net. If NSData(contentsOfFile:) fails, the conditional will be false, the webView will not load the data and your app will not crash.

2 Likes

The pathForResource() method returns a so-called optional because it is possible that there is no such file BullsEye.html in the application bundle (of course we know there will be, but Swift doesn’t know that).

The if let statement unwraps that optional and turns it into an actual variable, but only if that BullsEye.html file could be found.

Much more about this is explained in the follow-up tutorials. Optionals are an important feature of Swift!

1 Like

Now I got why “if” should be there for the method…thanks a lot.

Yup…now I remember optionals, I ever saw that when I went through Apprentice 2 first time…thank you very much for the help.