Xcode 游乐场无法访问“源”文件夹中的快捷文件

我刚升级到 Xcode 6.3他们给游乐场增加了新功能。如果创建一个新的游乐场并打开项目导航器,您将看到一个 Source 文件夹,其中有一个“ SupportCode.swift”文件。在那个文件的顶部

这个文件(和所有其他 Swift 源文件在这个游乐场的源目录)将被预编译成一个框架,这是自动提供给。游乐场。

我尝试把一个功能在那里,它是不可用的,我的操场。我做错了什么?我必须手动编译 SupportCode.swift 文件吗?怎么做到的?

37084 次浏览

You have to add public access attribute to your classes, methods and properties in source folder to make them accessible from main playground file as they treated as separate module by compiler

As mentioned when you create .swift files in Source folder they are automatically available to your playground code. To control the access of different parts of this file you can use Access level modifiers which are: public, internal & private.

According to Swift programming language access control

The default access level in most cases is internal which accessible inside the module, but not the outside.

In other words, if you declare a class without access modifier you can access it from another file in Source folder but NOT in your playground's main file. in other hand if you declare a class with public modifier you can access it in both cases.

for practical usage: let's make an Singleton implementation First: I create a new file in Source folder named 'Singy.swift' with following code:

public class Singy {
public var name = ""
private static var instance: Singy?
private init() {}


public static func getSingy() -> Singy {
if Singy.instance == nil {
Singy.instance = Singy()
}
return Singy.instance!
}
}

Second: from my playground

var s1 = Singy.getSingy()
var s2 = Singy.getSingy()
s1.name = "One"
print(s2.name)

Both s1 and s2 reference the same instance, but it created only within the class

Playgrounds are good for running tests. Put all your code in the Sources directory and have one publicly accessible 'test' class, for each test. Then run the publicly accessible tests from the playground.

playground

Test1.run()
Testx.run()
...

Sources/Test1.swift

public class Test1 {
public static func run() {
let my_class = MyClass()
let result = my_class.do_something()
print(result)
}
}

Sources/MyClass.swift

class MyClass {
func do_something() -> String {
return "lol"
}
}