我在项目的单独 Swift 文件中创建了最简单的自定义类:
class Foo
{
init()
{
println("I made a foo.")
}
}
然后,在同一项目的 Playground 上,我尝试了
var x = Foo()
Xcode 似乎不喜欢这样,并告诉我“Foo”是一个未解析的标识符。我对 playground 如何融入项目结构的其余部分感到有些困惑,因为我项目中的任何其他 Swift 文件都可以毫无问题地解析“Foo”。
如何让我的 playground 能够使用我在项目的其他 Swift 文件中定义的自定义类?我已尝试为构建目标命名产品模块并将其导入 Playground ,但没有成功: Playground 无法识别产品模块的名称。
在此先感谢您的帮助。我知道这很简单。
最佳答案
有两种方法可以在 Playground 中使用您的项目代码
Playground 的源文件夹
是的,在 Xcode 6.3 Beta 3 中(希望在未来):
Playgrounds are now represented within Xcode as a bundle with a disclosure triangle that reveals Resources and Sources folders when clicked. These folders contain additional content that is easily accessible from your playground’s main Swift code. To see these folders, choose View > Navigators > Show Project Navigator (or just hit Command-1).
打开一个新的 playground 并按 cmd + 1 以查看左侧 Pane ,然后将文件拖到 source
文件夹中以在 playground 中使用。
注意:
源文件夹中的文件被编译成一个框架,这意味着如果你想在 playground 中访问类、函数等,它们必须明确标记为 public
。
public class VisibleClass {
}
class InvisibleClass {
}
来源:release blog
将项目编译成框架
- 将项目移至工作区(如果尚未)。 (文件 -> 另存为工作区)就可以了
- 将框架目标添加到您的项目
- 构建框架
- 确保您要访问的文件已添加到您的框架目标
- 将 Playground 添加到工作区(不是项目)
- 使用
@testable import YourFrameworkName
- 在 playground 中访问代码
如果你想的话,我在这里写了一篇更详细的文章 check it out .
关于swift - Swift playgrounds 可以看到同一项目中的其他源文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24029090/