Class 游乐场内的扩展

Class extension inside a playground

我的 Playground 源文件夹中有一个 UIVIew 子class(它是一个 Public class),我试图只放一部分 class 作为扩展名进入我的主要游乐场文件。

当我在 playground 中声明以下内容时

public extension SortingAlgorithmView {

    public func typeTest() {
        print("dfasfndjasfasfdasfdasf test ")
    }
}

然后在我的 subclass 中调用 typeTest() 它告诉我没有名称为 typeTest 的函数。

交互式页面不 运行 在源文件旁边;源文件首先被编译,然后导入到你的 playground 页面中(这就是为什么你需要制作所有东西 public)。这使得它们更快,因为它们可以只编译一次而不是每次都解释,但这也意味着它们不能引用 playground 页面中的代码。

如果你想从源文件中访问扩展,你必须把它放在一个源文件中。源文件无法访问交互式内容。

这对我来说很好....

编辑: 好的,试一试 - 再一次,对我来说效果很好...

// extFuncs.swift --- 在源文件夹中

import UIKit

public extension SortingAlgorithmView {

    public func typeTest() {
        print("dfasfndjasfasfdasfdasf test ")
    }
}

public class SortingAlgorithmView: UIView {

}

// 游乐场中的一个页面

import UIKit
import PlaygroundSupport

let view = SortingAlgorithmView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
view.backgroundColor = UIColor.blue

view.typeTest()

PlaygroundPage.current.liveView = view