15

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
alexey
  • 343
  • 1
  • 4
  • 11

4 Answers4

45

As of Xcode 9.3+ Swift now supports #if targetEnvironment(simulator) to check if you're building for Simulator.

Please stop using architecture as a shortcut for simulator. Both macOS and the Simulator are x86_64 which might not be what you want.

// ObjC/C:
#if TARGET_OS_SIMULATOR
    // for sim only
#else
    // for device
#endif


// Swift:
#if targetEnvironment(simulator)
    // for sim only
#else
    // for device
#endif
Claus Jørgensen
  • 25,882
  • 9
  • 87
  • 150
russbishop
  • 16,587
  • 7
  • 61
  • 74
11

TARGET_IPHONE_SIMULATOR macro doesn't work in Swift. What you want to do is like the following, right?

#if arch(i386) || arch(x86_64)
let device = false
let RealmDB = try! Realm(path: "/Users/Admin/Desktop/realm/Realm.realm")
#else
let device = true
let RealmDB = try! Realm()
#endif
kishikawa katsumi
  • 10,418
  • 1
  • 41
  • 53
6

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
zontar
  • 485
  • 7
  • 18
0

More explanation about this issue is here. I am using this approach:

struct Platform {
        static let isSimulator: Bool = {
            var isSim = false
            #if arch(i386) || arch(x86_64)
                isSim = true
            #endif
            return isSim
        }()
    }

    // Elsewhere...

    if Platform.isSimulator {
        // Do one thing
    }
    else {
        // Do the other
    }

Or create a utility class:

class SimulatorUtility
{

    class var isRunningSimulator: Bool
    {
        get
        {
             return TARGET_OS_SIMULATOR != 0// for Xcode 7
        }
    }
}
donjuedo
  • 2,475
  • 18
  • 28
Oleg Gordiichuk
  • 15,240
  • 7
  • 60
  • 100
  • thank you for reply! the thing is that i can put that "if Platform.isSimulator" inside some class, yet i need to set that constant "let RealmDB..." on the top level right after "import RealmSwift". – alexey Mar 23 '16 at 14:45
  • Please do NOT use architecture as a shortcut for simulator. – russbishop Sep 26 '17 at 22:56