 import UIKit
 import WebKit
 
-var myContext = 0
-
 class WebViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
-
-    weak var webView: WKWebView?
-    weak var progressView: WebViewProgressView?
+    weak var webView: WKWebView!
+    weak var progressView: WebViewProgressView!
     @IBOutlet weak var backBarButton: UIBarButtonItem!
     @IBOutlet weak var forwardBarButton: UIBarButtonItem!
     @IBOutlet weak var stopBarButton: UIBarButtonItem!
     @IBOutlet weak var refreshBarButton: UIBarButtonItem!
 
-    deinit {
-        webView?.removeObserver(self, forKeyPath: "loading")
-        webView?.removeObserver(self, forKeyPath: "title")
-        webView?.removeObserver(self, forKeyPath: "estimatedProgress")
-        webView?.removeObserver(self, forKeyPath: "canGoBack")
-        webView?.removeObserver(self, forKeyPath: "canGoForward")
-    }
+    private var keyValueObservations: [NSKeyValueObservation] = []
 
     override func viewDidLoad() {
         super.viewDidLoad()

        webView.uiDelegate = self
        webView.allowsBackForwardNavigationGestures = true
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        webView.addObserver(self, forKeyPath: "loading", options: .new, context: &myContext)
        webView.addObserver(self, forKeyPath: "title", options: .new, context: &myContext)
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: &myContext)
        webView.addObserver(self, forKeyPath: "canGoBack", options: .new, context: &myContext)
        webView.addObserver(self, forKeyPath: "canGoForward", options: .new, context: &myContext)
        view.addSubview(webView)
        self.webView = webView


        forwardBarButton.isEnabled = false
    }

    @IBAction func backBarButtonTapped(_ sender: AnyObject) {
        if webView.canGoBack {
            webView.goBack()
        }
    }

    @IBAction func forwardBarButtonTapped(_ sender: AnyObject) {
        if webView.canGoForward {
            webView.goForward()
        }
    }

    @IBAction func stopBarButtonTapped(_ sender: AnyObject) {
        if webView.isLoading {
            webView.stopLoading()
        }
    }

    @IBAction func refreshBarButtonTapped(_ sender: AnyObject) {
        _ = webView.reload()
    }

    // MARK: - WKNavigationDelegate methods
