如何确定Swift代码是否在XCode Playground中运行

时间:2023-01-23 17:48:11

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.

我正在编写一个简单的应用程序,在Swift中读取CSV文件,我希望能够在Playground中使用相同的代码,并将其作为swift命令的输入文件。

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

要在Playground中读取文件,我必须使用此代码

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

1 个解决方案

#1


3  

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....

#1


3  

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....