Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Swift 5

You're reading from   Mastering Swift 5 Deep dive into the latest edition of the Swift programming language

Arrow left icon
Product type Paperback
Published in Apr 2019
Publisher Packt
ISBN-13 9781789139860
Length 370 pages
Edition 5th Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Preface 1. Taking the First Steps with Swift FREE CHAPTER 2. Learning about Variables, Constants, Strings, and Operators 3. Optional Types 4. Using Swift Collections 5. Control Flow 6. Functions 7. Classes, Structures, and Protocols 8. Using Protocols and Protocol Extensions 9. Protocol Oriented Design 10. Generics 11. Availability and Error Handling 12. Custom Subscripting 13. Working with Closures 14. Concurrency and Parallelism in Swift 15. Custom Types 16. Memory Management 17. Swift Formatting and Style Guider 18. Adopting Design Patterns in Swift 19. Other Books You May Enjoy

Playgrounds

When I was a kid, the best part of the school day was going to the playground. It really did not matter what we were playing as long as we were on the playground. When Apple introduced playgrounds as part of Xcode 6, I was excited just by the name, but I wondered whether Apple would be able to make its playgrounds as fun as the playgrounds of my youth. While Apple's playgrounds might not be as fun as playing kickball when I was nine years old, it definitely brings a lot of fun back to experimenting and playing with code.

Playgrounds are also available for the iPad. While we are not going to cover the iPad version specifically in this section, the iPad version is a great way to experiment with the Swift language and is a great way to get children interested in programming.

Getting started with playgrounds

Playgrounds are interactive work environments that let us write code and see the results immediately as changes are made to the code. This means that playgrounds are a great way to learn and experiment with Swift. Now that we can use Swift Playgrounds on the iPad, we do not even need to have a computer in front of us to experiment with Swift.

If you are using Swift on the Linux platform, you will not have playgrounds available, but you can use the Read-Evaluate-Print-Loop (REPL) shell to experiment with Swift without compiling your code. If you are using Swift on something other than a macOS computer or the iPad, you can safely skip this section.

Playgrounds also make it incredibly easy to try out new APIs, prototype new algorithms, and demonstrate how code works. We will be using playgrounds throughout this book to show how our sample code works. Therefore, before we really get into Swift development, let's spend some time learning about, and getting comfortable with, playgrounds.

Do not worry if the Swift code does not make a lot of sense right now; as we proceed through this book, the code that we use in the following examples will begin to make sense. We are simply trying to get a feel for playgrounds right now.

A playground can have several sections, but the three that we will be using extensively in this book are the following:

  • Coding Area: This is where you enter your Swift code.
  • Results Sidebar: This is where the results of your code are shown. Each time you type in a new line of code, the results are re-evaluated, and the Results Sidebar is updated with the new results.
  • Debug Area: This area displays the output of the code, and it can be very useful for debugging.

The following screenshot shows how these sections are arranged in a playground:

Let's start a new playground. The first thing we need to do is start Xcode. Once Xcode has started, we can select the Get started with a playground option, as shown in the following screenshot:

Alternatively, we can navigate to the Playground... by going to File | New from the top menu bar, as shown in the following screenshot:

Next, we should see a screen similar to the following screenshot. This screen lets us name our playground and select whether the playground is an iOS, tvOS, or macOS playground. For most of the examples in this chapter, it is safe to assume that you can select any of the OS options unless it is otherwise noted. You can also select a template to use. For the examples in this book, we will be using the Blank template for all of our code:

Finally, we are asked for the location in which to save our playground. After we select the location, the playground will open and look similar to the following screenshot:

In the preceding screenshot, we can see that the coding area of the playground looks similar to the coding area for an Xcode project. What is different here is the sidebar on the right-hand side. This sidebar is where the results of our code are shown. The code in the previous screenshot imports the Cocoa framework since it is a macOS playground. If it were an iOS playground, it would import the UIKit framework instead.

If your new playground does not open the debug area, you can open it manually by pressing the shift + command + Y keys together. You can also close the debug area by pressing shift + command + Y again. Later in this chapter, we will see why the debug area is so useful. Another way to open or close the debug area is to click on the button that looks like an upside-down triangle in a box that is on the border between the debug area and the coding area.

iOS, tvOS, and macOS playgrounds

When you start a new iOS or tvOS playground, the playground imports the UIKit framework. This gives us access to the UIKit framework, which provides the core infrastructure for iOS and tvOS applications. When we start a new macOS playground, the playground imports the Cocoa framework.

What the last paragraph means is that, if we want to experiment with specific features of either UIKit or Cocoa, we will need to open the correct playground. As an example, if we have an iOS playground open and we want to create an object that represents a color, we would use a UIColor object. If we had a macOS playground open, we would use an NSColor object to represent a color.

Showing images in a playground

It is very easy to receive the results of our code as text within the results sidebar of a playground; however; they can also do a lot more than just work with text. We can display other items, such as images and graphs. Let's look at how we would show an image in a playground. The first thing we need to do is to load the image into the resource directory of our playground.

The following steps show how to load an image into the resource directory:

  1. Show the project navigator sidebar. To do this, in the top menu bar, navigate to View | Navigators | Show Project Navigator or use the command + 1 keyboard shortcut. The project navigator looks similar to this:
  1. In the Project Navigator, drag the image into the Resources folder so that we can access it from our code. Once we drag the image file over it and drop it, it will appear in the Resources folder, as shown here:
  1. Let's access the image that is in our Resources folder within our code. The following screenshot shows how we would do this. At this time, the code that was used to access the image is not as important as knowing how to access resources within a playground:
  1. To view the image, we need to hover our cursor in the Results Sidebar over the section that shows the width and height of the image. In our example, the width and height section shows w 256 h 256. Once we hover the mouse pointer over the width and height, we should see two symbols next to the width and height. One looks like an eye and the other is a box. The following screenshot shows these:
  1. We can press either of the symbols to show the image. The one that looks like a box within a box will display the image within the playground's code section, while the one that looks like an eye will pop the image up outside the playground. The following screenshot shows what it looks like if we display the image within the playground:

Having the ability to create and display graphs can be very useful when we want to see the progression of our code. Let's look at how we can create and display graphs in a playground.

Creating and displaying graphs in playgrounds

Creating and displaying graphs is really useful when we are prototyping new algorithms because it allows us to see the value of a variable throughout the course of our calculations. To see how graphing works, look at the following playground:

In this playground, we set the j variable to 1. Next, we create a for loop that assigns numbers 1 through 5 to the i variable. At each step in the for loop, we set the value of the j variable to the current value of j multiplied by i. The graph shows the values of the j variable at each step of the for loop. We will be covering for loops in detail later in this book.

To bring up the graph, click on the symbol that is shaped like a circle with a dot in it. We can then move the timeline slider to see the values of the j variable at each step of the for loop. The following playground shows what the graph should look like:

What playgrounds are not

There is a lot more that we can do with playgrounds, and we have only scratched the surface in our quick introduction here. Before we leave this brief introduction, let's take a look at what playgrounds are not so that we can better understand when not to use playgrounds:

  • Playgrounds should not be used for performance testing: The performance you see from any code that is run in a Playground is not representative of how fast the code will run when it is in your project
  • Playgrounds do not support on-device execution: You cannot run the code that is present in a playground as an external application or on an external device
You have been reading a chapter from
Mastering Swift 5 - Fifth Edition
Published in: Apr 2019
Publisher: Packt
ISBN-13: 9781789139860
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image