Swift 4 Adding Value-changing Undo in the Undo Stack


Hey, I have been reading through the forum until Chapter 11. I had great help to make my programs work, thank you!

And for this chapter, there was some difficulty dealing with the syntax change in Swift 4, especially with the “PrepareWIthInvocationTarget” method. I tried to make it work for three days, and somehow I managed to do so with Swift 4. Here is my code if anyone is interested(for the function observing key value )

>      override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
>             if context != &KVOContext {
>                 super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
>                 return
>             }
>             else {
>                 Swift.print("Emlpoyee data changed.")
>                 var oldValue: Any? = change?[NSKeyValueChangeKey.oldKey]
>                 if oldValue is NSNull {
>                     oldValue = nil
>                 }
>                 Swift.print("Old Value is \(String(describing: oldValue))")
>                 Swift.print("Key path is \(String(describing: keyPath))")
>                 Swift.print("This object is \(String(describing: object))")
>                 ((undoManager!.prepare(withInvocationTarget: object) as! Any) as AnyObject).setValue(oldValue, forKey: keyPath!)
>                 }
>             }

******Preformatted text
Compared to the code provided by the text, I unwrapped the employee target to non-optional Any, and then converted it to AnyObject. Then it seems to be calling the setValue method. I am new to Swift, no sure why we need to convert an invocation target twice. And convert the target to Employee caused crash. Let me know if you understand it. Hope it helps if you are struggling, mine worked!