Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing classes from playground page into another page

Note: This is a different question than importing generic swift files (which can be done using the Sources folder).

I have a playground with 2 pages and I would like to use a protocol defined in the first page in the second page. I'll use an example of JSON conversion.

JSON.xcplaygroundpage

import Foundation

protocol JSONConvertible {
    func jsonValue() -> String
}

JSONArray.xcplaygroundpage

import Foundation

//Undeclared type JSONConvertible
extension Array : JSONConvertible {

}

I have tried the following imports:

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

I have also tried adding JSON.xcplaygroundpage into the Source folder of JSONArray as well as the Resources folder.

Note: I realize that I could put the protocol definition in a separate JSON.swift and include that in my project Sources folder. That doesn't really answer my question.

like image 464
Kevin Avatar asked Aug 13 '15 17:08

Kevin


People also ask

How do I add a playground to my Xcode project?

To open Playground on Xcode, navigate to File in the menu and click on New > Playground... To test our square function, we will choose the Blank template. Name your Playground file, then click on Create.


1 Answers

This is working in Xcode 8.3.3.

For code common to multiple pages, put it in separate files under top-level Sources group. Be sure to have proper Swift access control keywords in the right places.

Note from http://help.apple.com/xcode/mac/8.2/#/devfa5bea3af:

...the auxiliary Swift source file must export it using the public keyword. This includes classes, methods, functions, variables, and protocols.

playground source file Common.swift:

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

Then you can reference it in all of the other pages. Like this:

playground page Page2:

//: [Previous](@previous)

let d = DoIExist()

//: [Next](@next)

You can see that it works because of the console output ("Woot!") and the view results gutter.


To achieve this, I followed the directions at the Apple Xcode documentation about Playgrounds. When Apple inevitably moves those docs and does not provide a forwarding link, read on for how I found it.

I searched for the clues found in the link in cocoapriest's answer: "ios recipes Playground Help Add Auxilliary Code to a Playground". This leads to a document Apple is currently calling "Xcode Help" in a chapter titled "Use playgrounds" in a section titled "Add auxiliary code to a playground".

like image 122
Jeff Avatar answered Sep 28 '22 00:09

Jeff