Reference class / struct in a Playground page Xcode 7 Beta 1

Hello everyone! I'm loving the new Playground pages feature! The only issue I found so far is that - apparently - I cannot refer to anything declared in another page. Shared sources are all right, but wouldn't work for what I'm trying to do: I want to explain a topic in one page and build on top of that in the following page.


For example, assume you're teaching Algorithms, you might want to have a page that explains Queues and Stacks. In another page you might want to explain the BFS algorithm to traverse trees and graphs. To implement BFS you need a Queue and of course you'd like to reuse the implementation you wrote in the previous page. As far as I can see playing with the first beta of Xcode 7 (7A120f), this isn't currently possible. It seems that every page is a self-standing playground and they just happen to be bundled together.


Am I right or is there a way to reference classes, structs, etc. from one Playground page in another page in the same Playground? If not, is it a feature we can expect by the time Xcode 7 comes out of beta?

Replies

Me, too. I have the same question.


(If there is a more appropriate way to mark a forum question as "me, too", I will gladly do so.)

I have a truly awful workaround. It is fragile, awkward, and probably evil.


But I have had some (limited) success with the following trick. Suppose my "PageFour" needs to see what is in PageThree and PageTwo.


  1. Be sure to use "public" for any objects that you want to be availble to other pages.
  2. First get into (and possibly create) the Sources folder for PageFour
    $ cd MyPlayground.playground/Pages/PageFour.xcplaygroundpage/Sources
  3. Link in Contents from other Pages
    $ ln -s ../../PageTwo/Contents.swift PageTwoPage.swift
    $ ln -s ../../PageThree/Contents.swift PageThreePage.swift


One (of several) things to note about this solution is that it effects are not transitive. If PageFive will need stuff from PageTwo and PageThree, it is is not enough to merely link in PageFour.


Also, I do not know how well the zipping and unzipping of a playground will preserve the symbolic links. (I picked soft links instead of hard links in the hopes that the soft links would stand a better chance of being presevered while zipping).


I really can't recommend this solution. But I'd broken up a long playground into pages and wrote a lot of additional text before I learned about this problem. So if my solution reeks of desparation, it is because I was desparate.

Each page runs as a separate application. If you want to share code /structures, they must go into the shared Sources folder and not the page-by-page folder.


You can confirm the page-by-page apps by looking at NSBundle().mainBundle.executablePath for each page.