title: How to use KVO for UserDefaults in Swift?
body: <p>I'm rewriting parts of an app, and found this code:</p>
  
  <pre><code>fileprivate let defaults = UserDefaults.standard
  
  func storeValue(_ value: AnyObject, forKey key:String) {
      defaults.set(value, forKey: key)
      defaults.synchronize()
  
      NotificationCenter.default.post(name: Notification.Name(rawValue: "persistanceServiceValueChangedNotification"), object: key)
  }
  func getValueForKey(_ key:String, defaultValue:AnyObject? = nil) -&gt; AnyObject? {
      return defaults.object(forKey: key) as AnyObject? ?? defaultValue
  }
  </code></pre>
  
  <p>When CMD-clicking the line <code>defaults.synchronize()</code> I see that <code>synchronize</code> is planned deprecated. This is written in the code:</p>
  
  <pre><code>/*!
       -synchronize is deprecated and will be marked with the NS_DEPRECATED macro in a future release.
  
       -synchronize blocks the calling thread until all in-progress set operations have completed. This is no longer necessary. Replacements for previous uses of -synchronize depend on what the intent of calling synchronize was. If you synchronized...
       - ...before reading in order to fetch updated values: remove the synchronize call
       - ...after writing in order to notify another program to read: the other program can use KVO to observe the default without needing to notify
       - ...before exiting in a non-app (command line tool, agent, or daemon) process: call CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication)
       - ...for any other reason: remove the synchronize call
       */
  </code></pre>
  
  <p>As far as I can interpret, the usage in my case fits the second description: synchronizing <em>after</em> writing, in order to notify others.</p>
  
  <p>It suggests using KVO to ovserve, but how? When I search for this, I find a bunch of slightly older Objective-C-examples. What is the best practice for observing UserDefaults?</p>