2

In the following sample code, if remove the underscore in the webViewDidFinishLoad declaration, it doesn't fire. What does the underscore do?

import UIKit

class ViewController: UIViewController, UIWebViewDelegate {
  @IBOutlet weak var playerWebView: UIWebView!

  let youtubeUrl = URL(string: "https://youtube.com")

  override func viewDidLoad() {
    super.viewDidLoad()
    playerWebView.delegate = self

    let request = URLRequest(url: youtubeUrl!)

    playerWebView.loadRequest(request)

    print("viewDidLoad")
  }

  func webViewDidFinishLoad(_ playerWebView: UIWebView) {
    print("webviewFinishedLoad")
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
}
Geuis
  • 41,122
  • 56
  • 157
  • 219

1 Answers1

6

The underscore means that parameter name should be omitted when calling the function.

So this function:

func webViewDidFinishLoad(_ playerWebView: UIWebView) { /* ... */ }

should be called as:

webViewDidFinishLoad(aWebView)

and this one:

func webViewDidFinishLoad(playerWebView: UIWebView) { /* ... */ }

as:

webViewDidFinishLoad(playerWebView: aWebView)

In Swift, those are seen as two different functions and that's why you don't see the function being called when you change its signature.

More information can be found here, under "Function Argument Labels and Parameter Names":

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID166

Matusalem Marques
  • 2,399
  • 2
  • 18
  • 28