Creating an Xcode Project with a Built-in Playground

Playgrounds in Xcode can be pretty great. They let you quickly check how code works in the most practical way—by using it! It can save you a lot of time poring over documentation or getting stuck in Stack Overflow time sinks. It’s definitely been a big help as I put together my new app for musicians.

Everyone learns differently, but for me, the opportunity to test out code in a “scripty” way is really fantastic. That said, it’s a little tricky to integrate a playground into your Xcode projects such that it can actually access your classes. After trying some different approaches, here’s the workflow I use:

  1. In Xcode, File -> New -> Project… and then iOS -> Application -> Single View Application. Make sure the language is Swift; here are some sample settings:
    • Product name: SuperProject
    • Organization name: Big Apps, Inc.
    • Organization identifier: com.bigapps
    • Language: Swift
    • Devices: Universal
    • Options: Unit tests
  2. File -> Save as Workspace… Save it as SuperProject.xcworkspace in the same directory as SuperProject.xcproject file.
  3. File -> New -> File… and then iOS -> Source -> Playground. Call it SuperProject.playground, use the same directory as SuperProject.xcproject, and select the top-level “SuperPlayground” under Group (this is not the default option).
  4. File -> New -> Target… and then iOS -> Framework & Library -> Cocoa Touch Framework. Name it SuperPlaygroundiOS and uncheck Unit Tests.
  5. Optional: Control-click on ViewController.swift in the Project Navigator1 and click New File… and then iOS -> Source -> Swift File. Call it SuperClass.swift and make sure SuperProject and SuperProjectiOS are checked under Targets. Replace the contents of this file with this:
  6. import Foundation

    class SuperClass{
        func greetMe() -> String{
            return "Hello"
        }
    }

  7. Select the framework target (SuperPlaygroundiOS) in the File Inspector for any other files you want to access from your new playground.
  8. Select SuperPlaygroundiOS > iPhone 6S Plus beside the Play/Stop buttons, then Product -> Build.
  9. Scheme

  10. In SuperProject.playground, type the following at the top of the file:

    @testable import SuperPlaygroundiOS

    If you did step #5, you can now type this at the bottom of the file too. :)

    SuperClass.greetMe()

  11. IMPORTANT: Whenever you change your project, repeat steps 6 and 7 to access those changes in your playground.

This is tested for Xcode 7 and Swift 2.1. If you’ve found this useful or have any suggestions or comments, please share below!

1 This is just a quick way to ensure your new file will end up in the right directory/project.

2 thoughts on “Creating an Xcode Project with a Built-in Playground

Leave a Reply

Your email address will not be published. Required fields are marked *