在快速的游戏场地中复制声明

时间:2023-01-23 18:53:42

is there a way to introduce the concept of 'scope' while trying things out in playground?

有没有办法在游乐场尝试时引入“范围”的概念?

Say you want to test a couple of implementations of a class MyClass so you declare it, write some code to test things. You then decide you want to compare that with another version of class MyClass implementation.

假设您要测试MyClass类的几个实现,以便声明它,编写一些代码来测试。然后,您决定要将其与另一个版本的MyClass实现进行比较。

Redeclaring MyClass will give a redeclaration error.

重新声明MyClass将给出重新声明错误。

So can I have playground treat the first declaration of MyClass and associated code separately from the second without changing the class name or creating multiple playgrounds?

那么我可以让游乐场在不改变类名或创建多个游乐场的情况下将MyClass和相关代码的第一个声明与第二个声明分开处理吗?

thanks

2 个解决方案

#1


It's a bit of a hack, but you can use nested types for this – declare a struct the only purpose of which is to have this kind of scoping:

这有点像黑客,但你可以使用嵌套类型 - 声明一个结构,其唯一目的是具有这种范围:

struct Scope1 {
    class MyClass { }
}

struct Scope2 {
    class MyClass { }
}

let x = Scope1.MyClass()
let y = Scope2.MyClass()

// if you want to quickly switch between using 
// one vs the other
typealias MyClass = Scope1.MyClass
let z = MyClass()

#2


No, there isn't. Playground files are order-dependent and run in top-down lexical order.

不,没有。 Playground文件依赖于顺序,并以自上而下的词汇顺序运行。

#1


It's a bit of a hack, but you can use nested types for this – declare a struct the only purpose of which is to have this kind of scoping:

这有点像黑客,但你可以使用嵌套类型 - 声明一个结构,其唯一目的是具有这种范围:

struct Scope1 {
    class MyClass { }
}

struct Scope2 {
    class MyClass { }
}

let x = Scope1.MyClass()
let y = Scope2.MyClass()

// if you want to quickly switch between using 
// one vs the other
typealias MyClass = Scope1.MyClass
let z = MyClass()

#2


No, there isn't. Playground files are order-dependent and run in top-down lexical order.

不,没有。 Playground文件依赖于顺序,并以自上而下的词汇顺序运行。