What is wrong with my #if TARGET_OS_SIMULATOR code to determine the area path?

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 

The bool device works fine, but RealmDB only works for the rest of the conditions.

+11
source share
4 answers

TARGET_IPHONE_SIMULATOR macro does not work in Swift. What you want to do is this: "

 #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 
+11
source

Starting with Xcode 9. 3+ Swift now supports if #targetEnvironment(simulator) to check if you are building for a simulator.

Please stop using architecture as a shortcut for the simulator. Both macOS and Simulator have x86_64, which may not be what you need.

 // ObjC/C: #if TARGET_OS_SIMULATOR // for sim only #else // for device #endif // Swift: #if targetEnvironment(simulator) // for sim only #else // for device #endif 
+24
source

Please see this post. This is the right way to do it, and he explained well

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

Essentially, define a variable with a name of your choice (maybe "SIMULATOR"), which will be set during startup in the simulator. Set it to "Target Build Options", under " Active Compilation Conditions β†’" Debug then (+) then select " Any iOS Simulator SDK from the drop-down list and add a variable.

Then in your code

 var isSimulated = false #if SIMULATOR isSimulated = true // or your code #endif 
+6
source

A more detailed explanation of this problem is here . I use 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 } } } 
0
source

Source: https://habr.com/ru/post/1245632/


All Articles