What's wrong with my #if TARGET_OS_SIMULATOR code for Realm path definition?

Viewed 8674

I have this code

 #if TARGET_OS_SIMULATOR
let device = false
let RealmDB = try! Realm(path: "/Users/Admin/Desktop/realm/Realm.realm")
#else
let device = true
let RealmDB = try! Realm()
#endif

device bool works fine, yet RealmDB works only for else condition.

4 Answers

Please see this post. This is the correct way to do it and it's well explained

https://samsymons.com/blog/detecting-simulator-builds-in-swift/

Basically define a variable named as you like (maybe 'SIMULATOR') to be set during run in simulator. Set it in Build Settings of Target, under Active Compilation Conditions- > Debug then (+) then choose Any iOS Simulator SDK in the dropdown list, then add the variable.

Then in your code

var isSimulated = false
#if SIMULATOR
  isSimulated = true // or your code
#endif
Related