Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a Swift code is running inside XCode Playground

Tags:

swift

I'm writing a simple application reading CSV file in Swift and I would like to be able to use the same code in Playground and as an input file to the swift command.

To read a file in Playground I have to use this code

let filePath = XCPlaygroundSharedDataDirectoryURL.URLByAppendingPathComponent("data.csv")

I would like to achieve something like:

#if PLAYGROUND
import XCPlayground
let filePath = XCPlaygroundSharedDataDirectoryURL.URLByAppendingPathComponent("data.csv")
#else
let filePath = NSURL.fileURLWithPath("data.csv")
#endif
like image 416
Maciej Wozniak Avatar asked Oct 18 '22 13:10

Maciej Wozniak


1 Answers

The test is quite simple:

let bundleId = NSBundle.mainBundle().bundleIdentifier ?? ""
if bundleId.hasPrefix("com.apple.dt"){
        //... Your code
}

But I think you have already seen the problem once you've done that... the import will stop the build elsewhere. I suspect you are trying to build a playground for a framework you have built (if not, I'm not quite sure how the code is being shared)... The way I solved it in the framework was to provide an optional call back hook for the value I wanted to get... so for example

In Framework

public defaultUrlHook : (()->NSURL)? = nil

internal var defaultUrl : NSURL {
    return defaultUrlHook?() ?? NSURL.fileURLWithPath("data.csv")
}

In playground

import XCPlayground
import YourFramework

defaultUrlHook = { ()->NSURL in 
      return XCPlaygroundSharedDataDirectoryURL.URLByAppendingPathComponent("data.csv")
}

//Do your thing....
like image 177
rougeExciter Avatar answered Nov 15 '22 02:11

rougeExciter