So whilst researching for a new video I'm going to be doing switching between light and dark mode in a SwiftUI app I stumbled across a situation where it only seemed to be saving the dark mode flag some of the time on the simulator. The fact it worked some of the time was confusing. Naturally I thought I must have a bit of code that perhaps was causing this.
From previous encounters with UserDefaults and other developers the standard solution is to chuck in a call to Synchronise but it's clear in the documentation that this is no longer required and hasn't been for a long time. It also doesn't solve the issue.
I ripped out the property wrapper @AppStorage and implemented it in the old way using UserDefaults.standard and I still had the same issue. Beyond this being a major bug with iOS 14 or something I must have been missing something.
So it turned out because I was using CMD-R to rerun the app this is the equivalent of a crash essentially so the system does not have time to write the value which I assume it does on the app being normally terminated some of the time rather than a more unlikely occurrence of a crash.
So if you are running into this issue where the UserDefaults doesn't seem to be working properly it's most likely you just need to close and restart the app properly as though it is in production.