Get up and running with Swift playgrounds in Xcode 7

Update October 2015: Fully updated for Swift 2.1

The curtain came down on the annual WWDC and Apple has announced the new iOS 9 and Xcode 7 along with Swift 2 and major changes to its SDK libraries, debugging and development tools. In this tutorial, you will get hands-on several new stuff shipped on swift playgrounds with direct experiments to understand how they work.

Ready to go? let’s do it 🙂

First, download the latest Xcode 7 release from the Apple developer center.

Swift playgrounds:

Since Swift was launched to the world, Xcode has shipped Swift playgrounds as the convenient tool to try out the language features and pattern. You can use playgrounds to rapidly make a class and extensions and test them right away, you can even import some frameworks from your existing Xcode project to experiment with, right from within the playgrounds files and pages, without messing with your app code.

I just prepared a ready-to-go playground to play with, download it here and open it with Xcode 7.

Take a look at the code in there, basically it’s a simple class implementation which create, initialise and print out a tutorial informations.

  • Rich comments
  • In Xcode 7, Apple introduced a bench of new features to make playgrounds even better to use, one of them is Rich Comments.

    Rich Comments let you explain what is going on in your swift code in a better way, with a markdown-like syntax, so that you can control your comments appearance and produce a code which is easy to understand.

    Let’s add some rich comments to the class to make it more documented and beautiful to read.

    At the very top of the class (before the import clause), place the following comment code:

    /*:
    This is made to show you the new features which Xcode 7 has brought to Swift playground.
    # Rich comment, Results view, Pages..
    */
    

    Playground will instantly run your code and reflect the relevant changes to you.

    Get up and running with iOS 9, Xcode 7 and Swift 2

    Oups, if you see no changes to your playground, you most likely need to switch to the “Rendered Markup” mode. To do so, select “Editor\Show Rendered Markup” from the menu.

    Rich comment for Swift Playground

    Here you go, Xcode now format the comments in a nice way, similar to the way they did with their online docs.

    As you may notice, you just need to add a colon (:) to tell Xcode that you want to format a rich comment instead of a normal comment. Also, the number sign (#) is used to specify heading, we can specify up to three level of heading (#, ##, ###)

    Try it out, place the following rich comment line right after the class name:

    //: ### Properties
    

    Next, copy the following line before the init method:

    //: ### Init and Methods
    

    And another rich comment line right after the closing bracket of the class:

    //: ### Class instantiation
    

    Note 1: In order to better edit your code and reflect comment layout in playground, you may need to switch between markup modes from within the Editor menu (“Show Raw Markup” and “Show Rendered Markup”).

    Note 2: Comments in playground are whitespace-sensitive, make sure that the comment lines are in the left of the line and that no white space is leading the comment.

    After you switch to the rendered markup, you should see something like the following:

    Rich comments with heading

    This is absolutely much more better 🙂

    We just experiment with the main idea of rich comments. Yet, there is lot more options for rich comments and markup syntax. If you want to customise your comments with more fancy ways, I recommend you head over to the official Playground Markup Format for Comments document.

  • Results view
  • In addition to the Quick Look feature, Swift playgrounds now enables Results view.

    Results view display an instant result which is close to the format of the result you are supposed to see. For example, if you load an image in the code, you will instantly see that image rendered inside the code editor.

    Let’s try it 🙂

    Download this image, then drag and drop it inside the Resources bundle in playground.

    Note: If you don’t see the Resources bundle, you can reveal it by selecting ‘View\Navigators\Show Navigator’ from the menu (or select the cmd+0 shortcut).

    Now, in the code, add a UIImage variable declaration below the other vars:

    var tutorialImage:UIImage!
    

    Then, copy the image initialisation below, right after the class instantiation (before tuto.aboutTutorial() call):

    tuto.tutorialImage = UIImage(named: "img.png")
    

    Cool, now place the cursor to the line of code you added above and select ‘Editor\Show Result for Current Line’ from the menu.

    <em>Results view</em> display an instant result which is close to the format of the result you are supposed to see.

    As you can see, the image is added to the editor below the UIImage initialisation statement. You can view it on bigger size by clicking the eye icon next to the image as we did above. Results view also comes in handy if you want to visualise the result of changed values (loops for instance), in such case, the results view will draw a fancy graph with axes representing the iterated values during the loop iterations.

    The use of Results view is valid for all objects, don’t forget to continuously use it as you write code in your playground. For more informations about Results view, feel free to read the relevant reference documentation here.

  • Pages
  • Pages is a great way to create content that progresses through a topic. For example, we can divide our playground into different pages, let’s say one page will take care of author, the next page will focus on the tutorial itself, and another page for the keywords and topics of the tutorials.

    Let’s quickly add few pages to our existing playground. Make sure the Project navigator is shown in the left side, then select ‘File\New\Playground Page’ from the menu.

    Adding Pages in Playground

    Two pages are actually added. The first one (Untitled Page) is the current content of the playground editor, and the second one is the new page. Rename the first page to “Tutorial” and the second page to “Author”.

    Now, let’s have a look at the Author page:

    playground pages have previous and next links

    A “Previous” and “Next” links are put automatically on each new page you create in the playground. They will link to the previous and the next page in the Project navigator respectively. If you try to click on the “Previous” link, the “Tutorial” page will be loaded since it’s above the “Author” page in the Project navigator.

    However, if you click on the “Next” link, nothing will happen, this is obvious since there is no page under the “Author” page in the Project navigator.

    Let’s add another page to link to the “Author” page.

    Select ‘File\New\Playground Page’ from the menu or simply “cmd+alt+N”. Name the page “Topic”. Now if you click on the “Next” link inside the “Author” page, the “Topic” page will be loaded automatically. Xcode will detect and link pages instantly as they are created in the Project navigator.

    Let’s finish by linking the “Tutorial” page to the “Author” page so that we get three pages inter-connected. Select the “Tutorial” page from the Project navigator and place the following link markup line at the end of the file:

    //: [Next](@next)
    

    Make sure to select ‘Editor\Show Rendered Markup’ from the menu so that the link is rendered inside the page. Now you can navigate between all three pages you created in the playground 🙂

    Note: Links are another type of the markup syntax used for the Rich comments we saw previously in this tutorial. You can read more about Page navigation here.

    Playground pages are suitable for progressive content, it’s like a book with a summary, chapters and glossary. You can do the same with Playground pages. If you lead a team of developers, playground pages will come in handy to explain a concept or an idea to the team members, so take advantage of them to save time and to get more professional.

  • Auxiliary Sources
  • Playgrounds introduced a new way to manage swift code out of playground pages and import it as modules. This way, you can keep the message of the playground clearer to understand.

    For example, if you teach swift programming, you may want to develop some classes and functions that you work with but that students don’t need to see or know about. All such code can be developed in auxiliary files which will be compiled instantly as you save your work inside, and most importantly, they are compiled and executed faster than pages 🙂

    Let’s add an auxiliary source file to the “Tutorial” page.

    Make sure the Project navigator is shown, click on the disclosure triangle next to the “Tutorial” page to reveal the Sources and Resources bundles. Select the Sources folder then select ‘File\New\File’ from the menu, or click the Add button (+) in the lower-left corner of the window and choose ‘File’ from the pop-up menu that appears.

    A new swift file is placed on the Sources folder under the “Tutorial” page. Rename it to “TutorialExtraFunctions.swift”.

    Add auxiliary source to page in playground

    Now, make sure the TutorialExtraFunctions file is selected so that it is loaded in the source editor of the playground window, then place the following code after the import statement:

    public func aboutTutorial(title: String, author: String, publicationDate:NSDate)->String{
    
        return ("The tutorial '\(title)' written by \(author) was published in \(publicationDate)")
    }
    

    You just moved this method from the “Tutorial” page to the auxiliary source file “TutorialExtraFunctions”. It’s important to export the function with the access level keyword “public” so that we can import it from within the “Tutorial” page scope. Make sure to select ‘File\Save’ from the menu to compile the auxiliary source file.

    Now, select the “Tutorial” page and add the following line after the class instantiation:

    let aboutTuto:String = aboutTutorial(tuto.title, author: tuto.author, publicationDate: tuto.publicationDate)
    

    Obviously, you should remove the old “aboutTutorial” function code from there as well.

    You will notice the function call is processed instantly and the result is shown in the right view of the playground. This is the same result, except that it’s now processed from an auxiliary source file and it’s treated as a module which is compiled and executed more quickly 😉

    Here is the final code of the “Tutorial” page:

    /*:
    This is made to show you the new features which Xcode 7 has brought to Swift playground.
    # Rich comment, Results view, Pages..
    */
    
    import UIKit
    
    class Tutorial {
    //: ### Properties
       
        var title:String!
        var author: String!
        var publicationDate:NSDate!
        var tutorialImage:UIImage!
    
    //: ### Init and Methods
    
        init (withTitle title:String, author:String, publicationDate: NSDate){
            
            self.title = title
            self.author = author
            self.publicationDate = publicationDate
        }
    }
    //: ### Class instantiation
    
    var tuto = Tutorial(withTitle: "Get up and running with iOS 9, Xcode 7 and Swift 2", author: "Malek", publicationDate: NSDate())
    let aboutTuto:String = aboutTutorial(tuto.title, author: tuto.author, publicationDate: tuto.publicationDate)
    
    tuto.tutorialImage = UIImage(named: "img.png")
    
    //: [Next](@next)
    

    Where to go from here

    You can download the final swift playground project here.

    Playground is a powerful tool to teach with. It’s the best place not only to try out some code, but also to develop a concept/idea with all frameworks available for you. You can develop a game prototype from within the swift playground or you can develop a quick demo including fancy animations as they will appear on your final app to show to your team or client. Ideas are endless.

    In the next tutorial, I will go through Swift 2, the new release of the Swift language. You will experiment “Error Handling”, “Availability”, “Protocol extensions” and much more. One more part is being prepared for you to master new empowering debugging tools in Xcode 7, especially the amazing “address sanitizer” feature. So stay tuned 🙂

    Do you think playgrounds are getting better since last year? How often do you use them? Leave a comment below, I’d love to hear your thoughts!

    Malek
    iOS developer with over than 11 years of extensive experience working on several projects with different sized startups and corporates.

    6 Comments

    1. Stupid newbie question. Is The newest xcode in the beta stages ? I read that you can not submit apps using a beta version of xcode.

    2. Hi 🙂

      That is true, you cannot compile for iTunes connect using a beta version of Xcode, you need to wait for a release version of Xcode 7 or submit it with Xcode 6 for the moment.

    3. Really nice tutorial, short and well written. Learning how to view modified and filtered image directly from playground, priceless. Show result of current line? Who knew.

    Comments are closed.