How to determine if Swift code works inside the Xcode Playground

I am writing a simple application that reads a CSV file in Swift, and I would like to be able to use the same code in the Playground as an input file for the swift command.

To read the file on the 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 
+5
source share
1 answer

The test is pretty simple:

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

But I think you already saw the problem as soon as you did this ... import will stop the assembly elsewhere. I suspect that you are trying to build a playground for the structure you created (if not, I'm not quite sure how the code is divided). The way I solved this as part of the framework was to provide an extra hook call 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 the playground

 import XCPlayground import YourFramework defaultUrlHook = { ()->NSURL in return XCPlaygroundSharedDataDirectoryURL.URLByAppendingPathComponent("data.csv") } //Do your thing.... 
+3
source

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


All Articles