Chapter 5 - 'show_hint' conditional crashes app in iOS target

On page 104 (in v.1.1.0), when adding conditional for ‘if defaults.bool(forKey: “show_hint”)’, it worked fine when running on MacCatalyst (My Mac), but when I went back to trying to run the Preview for an iPhone, the app kept crashing. It seemed to have a problem with the ‘defaults’ property (UserDefaults) when the target was not MacCatalyst.

But I figured out a cure! In ContentView.swift, above the ContentView struct declaration, I added the following compiler conditional:

#if targetEnvironment(macCatalyst)
let ISMACCATALYST = true
#else
let ISMACCATALYST = false
#endif

Then in ContentView’s body, I wrapped the ‘show_hint’ conditional inside an ISMACCATALYST conditional, like this:

if ISMACCATALYST {
‘the show_hint if-else conditional’
} else {
Slider(value: $currentValue, in: 0.0…100.0, step: 1.0)
}

That did the trick. Just thought I’d put this out there in case anyone else ran into this.

thanks Michael! I must admit, I didn’t go back and try the iOS preview after adding Prefs to the MacCatalyst app :woman_facepalming:

the app runs in an iOS simulator, no probs, but it seems the canvas preview lacks permission to access UserDefaults. Which is odd, as preview seems to fire up Simulator.

here’s something to look forward to: I tried this app on my MacBook running Catalina beta, and even the MacCatalyst version hangs — can’t access user defaults!

It works for me in simulator on “My Mac” on my iMac running the latest beta OS.

thanks, you’re right! there’s another update waiting for me :slight_smile:

update: 10.15.3 beta, Xcode 11.3: both MacCatalyst and iOS-in-preview work!