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
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....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With