swift - 将类从 Playground 页面导入到另一个页面

标签 swift xcode swift-playground

注意:这是一个不同的question而不是导入通用的 swift 文件(可以使用 Sources 文件夹完成)。

我有一个有 2 页的 Playground ,我想在第二页中使用第一页中定义的协议(protocol)。我将使用 JSON 转换的示例。

JSON.xcplaygroundpage

import Foundation

protocol JSONConvertible {
    func jsonValue() -> String
}

JSONArray.xcplaygroundpage

import Foundation

//Undeclared type JSONConvertible
extension Array : JSONConvertible {

}

我尝试了以下导入:

import MyPlayground
import MyPlayground.JSON
import JSON
import JSON.Contents (in finder the file name is actually Contents.swift)

我还尝试将 JSON.xcplaygroundpage 添加到 JSONArray 的 Source 文件夹以及 Resources 文件夹中。

注意:我意识到我可以将协议(protocol)定义放在单独的 JSON.swift 中,并将其包含在我的项目 Sources 文件夹中。这并没有真正回答我的问题。

最佳答案

这适用于 Xcode 8.3.3。

对于多个页面通用的代码,将其放在顶级 Sources 组下的单独文件中。请务必在正确的位置使用正确的 Swift 访问控制关键字。

注释来自 http://help.apple.com/xcode/mac/8.2/#/devfa5bea3af :

...辅助 Swift 源文件必须使用 public 关键字将其导出。这包括类、方法、函数、变量和协议(protocol)。

playground source file Common.swift:

public class DoIExist { public init(){ print("Woot!")} }

然后您可以在所有其他页面中引用它。像这样:

playground page 第 2 页:

//: [Previous](@previous)

let d = DoIExist()

//: [Next](@next)

由于控制台输出(“Woot!”)和 View 结果槽,您可以看到它有效。


为了实现这一点,我遵循了 Apple Xcode documentation about Playgrounds 中的说明。 .当 Apple 不可避免地移动这些文档并且不提供转发链接时,请继续阅读我是如何找到它的。

我在 cocoapriest 的回答中搜索了链接中的线索:"ios recipes Playground Help Add Auxilliary Code to a Playground" .这导致 Apple 目前在标题为“将辅助代码添加到 Playground ”的部分中标题为“使用 Playground ”的章节中调用“Xcode 帮助”的文档。

关于swift - 将类从 Playground 页面导入到另一个页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31994390/

相关文章:

swift - Alamofire、ObjectMapper、Realm --> 在 Realm 中保存响应数据

ios - 多个 Storyboard - 多个导航 Controller

ios - 为同一个项目编译不同的代码 - Swift 框架

swift - 如何在 Pure Playground 文件中获取 CoreML

swift - swift 隐藏协议(protocol)的采用

ios - Swift:如何编写采用可选序列类型的枚举变体

Xcode clang 链接 : Build Dynamic Framework (or dylib) not embed dependencies

swift - 如何在 Playgrounds 中将 VC 设置为 Liveview?

swift - 在 Swift REPL 中导入 XCPlayground 模块

ios - 使用 Alamofire.upload 时出现段错误 : 11,