UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Day 25, Project 4 Part 2: Not really understand a code in observeValue()

Forums > 100 Days of Swift

Good day fellas.

I'm in Day 25 of the course, and having difficulties understanding how this line of code works

override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if keyPath == "estimatedProgress" {
        progressView.progress = Float(webView.estimatedProgress)
    }
}

So the part where

if keyPath == "estimatedProgress"

shows that observeValue() would monitor the change in value of estimatedProgress. However, isn't estimatedProgress a Double data type? How come converting that double to a string isn't something like String(estimatedProgress) or \(estimatedProgress) (you know, with string interpolation)? In fact, attempting these would make Xcode prompting an error Cannot find 'estimatedProgress' in scope 😯

I would appreciate it very much if anybody could kindly further elaborate how that line of code works!

P/s: The original link of the reading is https://www.hackingwithswift.com/read/4/4/monitoring-page-loads-uitoolbar-and-uiprogressview

3      

Hello,

to be honest KVO is not super pretty mechanism and since it exists from the ObjC times it has its pecularities. Paul has another article here you can check out - https://www.hackingwithswift.com/example-code/language/what-is-key-value-observing

What happens in the code you are using is that observeValue can be potentially called for multiple values that change. Here the "estimatedProgress" is not the value itself but rather the keypath which means basically name of the property, not its value. So with the if we know that this property changed and can read it directly from the webView.

I would not spend too much time on this, I cannot remember when I used KVO except for this use case.

4      

Thank you so much Filip 🙏🏻. It also dawned on me just now, that the observer was watching for changes in a key-value pair; in other words it means estimatedProgress is name of the key, not a value.

And then your post further consolidated that understanding. Hope you have a good day 😎

4      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.