Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there way for Swift code to detect if it's being run in a playground or not?

Tags:

swift

xcode7

To be able to test GameKit features, I'd like to be able to detect if the code is being run in a Playground, so that it can just skip the network calls. Is there a way to do this?

edit:

Forget about GameKit--that just muddies the issue. There are many different scenarios where this would be useful. It's really just a simple question about whether a specific function call exists or not: is there a method that returns true if the code is running in a Playground?

like image 865
Le Mot Juiced Avatar asked Nov 01 '25 05:11

Le Mot Juiced


1 Answers

I don't know of a documented way to do it, but there are some undocumented things you can do.

Here's a technique that works in both Xcode 7 with Swift 2.2 and Xcode 8 with Swift 3.0, in both macOS and iOS playgrounds: check for a bundle whose identifier starts with "com.apple.dt".

// Swift 2.2

if NSBundle.allBundles().contains({ ($0.bundleIdentifier ?? "").hasPrefix("com.apple.dt.") }) {
    print("in playground")
} else {
    print("not in playground")
}


// Swift 3.0

if Bundle.allBundles.contains(where: { ($0.bundleIdentifier ?? "").hasPrefix("com.apple.dt.") }) {
    print("in playground")
} else {
    print("not in playground")
}

Note that com.apple.dt. is not a prefix reserved specifically for a playground-related bundle; the dt part standards for something like “developer tool”. So there might be circumstances where you get a false positive: there's a bundle that matches but you're not in a playground. I'm not aware of any such circumstances, but there might be some. I did test an IBDesignable view in a macOS xib under Xcode 7, and it didn't have any com.apple.dt. bundles loaded.

like image 155
rob mayoff Avatar answered Nov 04 '25 02:11

rob mayoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!