Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Learning Swift Second Edition - Second Edition
Learning Swift Second Edition - Second Edition

Learning Swift Second Edition: Develop the skills required to create compelling, maintainable, and robust iOS and OS X apps with Swift, Second Edition

By Andrew J Wagner
€25.99 €17.99
Book Mar 2016 308 pages 2nd Edition
eBook
€25.99 €17.99
Print
€32.99
Subscription
€14.99 Monthly
eBook
€25.99 €17.99
Print
€32.99
Subscription
€14.99 Monthly

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 23, 2016
Length 308 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781785887512
Vendor :
Apple
Category :
Languages :
Table of content icon View table of contents Preview book icon Preview Book

Learning Swift Second Edition - Second Edition

Chapter 1. Introducing Swift

What are you trying to achieve by reading this book? Learning Swift can be fun, but most of us are trying to achieve something bigger. There is something we want to create, a career we want to follow, or maybe something else entirely. Whatever that goal is, I encourage you to keep it in mind as you read this book. It will be much easier for you to learn, from this or any other resource, if you can always relate it to your goal.

With that in mind, before we dive into learning Swift, we have to understand what it really is and how it will help us in achieving our goals. We also need to move forward with an effective learning technique and get a taste of what is to come. To do all of that, we will cover the following topics in this chapter:

  • Defining our goals for this book

  • Setting up the development environment

  • Running our first Swift code

  • Understanding playgrounds

  • Learning with this book

Defining our goals for this book


Swift is a programming language developed by Apple primarily to allow developers to continue to push their platforms forward. It is their attempt to make iOS, OS X, watchOS, and tvOS app development more modern, safe, and powerful.

However, Apple has also released Swift as Open Source and begun an effort to add support for Linux with the intent to make Swift even better and a general purpose programming language available everywhere. Some developers have already begun using it to create command-line scripts as a replacement/supplement of the existing scripting languages, such as Python or Ruby and many can't wait to be able to share some of their app code with Web backend code. Apple's priority, at least for now, is to make it the best language possible, to facilitate app development. However, the most important thing to remember is that modern app development almost always requires pulling together multiple platforms into a single-user experience. If a language could bridge those gaps and stay enjoyable to write, safe, and performant, we would have a much easier time making amazing products. Swift is well on its way to reach that goal.

Now, it is important to note that learning Swift is only the first step towards developing. To develop for a device, you must learn the programming language and the frameworks the device maker provides. Being skilled with a programming language is the foundation of getting better at using frameworks and ultimately building apps.

Developing software is like building a table. You can learn the basics of woodworking and nail a few pieces of wood together to make a functional table, but you are very limited in what you can do because you lack advanced woodworking skills. If you want to make a truly great table, you need to step away from the table and focus first on developing your skill set. The better you are at using the tools, the greater the number of possibilities that open up to you to create a more advanced and higher quality piece of furniture. Similarly, with a very limited knowledge of Swift, you can start to piece together a functional app from the code you find online. However, to really make something great, you have to put the time and effort into refining your skill set with the language. Every language feature or technique that you learn opens up more possibilities for your app.

That being said, most developers are driven by a passion to create things and solve problems. We learn best when we can channel our passions into truly improving ourselves and the world around us. We don't want to get stuck learning the minutia of a language with no practical purpose.

The goal of this book is to develop your skills and confidence to dive passionately into creating compelling, maintainable, and elegant apps in Swift. To do that, we will introduce the syntax and features of Swift in a practical way. You will build a rich toolset, while seeing that toolset put to real world usage. So, without further ado, let's jump right into setting up our development environment.

Setting up the development environment


In order to use Swift, you will need to run OS X, the operating system that comes with all Macs. The only piece of software that you will need is called Xcode (version 7 and higher). This is the environment that Apple provides, which facilitates development for its platforms. You can download Xcode for free from the Mac App Store at www.appstore.com/mac/Xcode.

Once downloaded and installed, you can open the app and it will install the rest of Apple's developer tool components. It is as simple as that! We are now ready to run our first piece of Swift code.

Running our first swift code


We will start by creating a new Swift playground. As the name suggests, a playground is a place where you can play around with code. With Xcode open, navigate to File | New | Playground… from the menu bar, as shown in the following screenshot:

Name it MyFirstPlayground, leave the platform as iOS, and save it wherever you wish.

Once created, a playground window will appear with some code already populated inside it for you:

You have already run your first Swift code. A playground in Xcode runs your code every time you make a change and shows you the code results in the sidebar, on the right-hand side of the screen.

Let's break down what this code is doing. The first line is a comment that is ignored while being run. It can be really useful in adding extra information about your code inline with it. In Swift, there are two types of comments: single-line and multi-line. Single-line comments, such as the preceding one, always start with a //. You can also write comments that span multiple lines by surrounding them with /* and */. For example:

/*
   This is a multi-line comment
   that takes up more than one line
   of code
*/

As you can see in the preceding screenshot, the second line, import UIKit, imports a framework called UIKit. UIKit is the name of Apple's framework for iOS development. For this example, we are not actually making use of the UIKit framework so it is safe to completely remove that line of code.

Finally, on the last line, the code defines a variable called str that is being assigned to the text "Hello, playground". In the results sidebar, next to that line, you can see that "Hello, playground" was indeed stored in the variable. As your code becomes more complex, this will become incredibly useful to help you track and watch the state of your code, as it is run. Every time you make a change to the code, the results will update, showing you the consequences of the change.

If you are familiar with other programming languages, many of them require some sort of line terminator. In Swift, you do not need anything like that.

The other great thing about Xcode playgrounds is that they will show you errors as you type them in. Let's add a third line to the playground:

  var str = "Something Else"

On its own, this is completely valid Swift code. It stores the text "Something Else" into a new variable called str. However, when we add this to the playground, we are shown an error in the form of a red exclamation mark next to the line number. If you click on the exclamation mark, you will be shown the full error:

This line is highlighted in red and we are shown the Invalid redeclaration of 'str' error. This is because you cannot declare two different variables with the exact same name. Also, notice that the results along the right turned gray instead of black. This indicates that the result being shown is not from the latest code, but the last successful run of the code. The code cannot be successfully run to create a new result because of the error. If we change the second variable to strTwo, the error goes away:

Tip

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

  • Log in or register to our website using your e-mail address and password.

  • Hover the mouse pointer on the SUPPORT tab at the top.

  • Click on Code Downloads & Errata.

  • Enter the name of the book in the Search box.

  • Select the book for which you're looking to download the code files.

  • Choose from the drop-down menu where you purchased this book from.

  • Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR/7-Zip for Windows

  • Zipeg/iZip/UnRarX for Mac

  • 7-Zip/PeaZip for Linux

Now the results are shown in black again, and we can see that they have been updated according to the latest code. Especially if you have experience with other programming environments, the reactiveness of the playground may be surprising to you. Let's take a peek under the hood to get a better understanding of what is happening and how Swift works.

Understanding playgrounds


A playground is not truly a program. While it does execute code like a program, it is not really useful outside of the development environment. Before we can understand what the playground is doing for us, we must first understand how Swift works.

Swift is a compiled language, which means that for Swift code to be run, it must first be converted into a form that the computer can actually execute. The tool that does this conversion is called a compiler. A compiler is actually a program and it is also a way to define a programming language.

The Swift compiler takes the Swift code as input and, if it can properly parse and understand the code, outputs machine code. Apple developed the Swift compiler to understand the code according to a series of rules. Those rules are what define the Swift programming language and those rules are what we are trying to learn, when we say we are learning Swift.

Once the machine code is generated, Xcode can wrap the machine code up inside an app that users can run. However, we are running Swift code inside our playground, so clearly building an app is not the only way to run code; something else is going on here.

Every time you make a change to a playground, it automatically tries to compile your code. If it is successful, instead of wrapping up the machine code in an app to be run later, it runs the code immediately and shows you the results. If you had to do this process yourself, you would first have to consciously make the decision to build the code into an app and then run it when you wanted to test something. This would be a huge waste of time; especially, if you write an error that you don't catch until the moment you decide to actually run it. The quicker you can see the result of a code change, the faster you will be at developing the code and the fewer mistakes you will make.

For now, we will be developing all of our code inside a playground because it is a fantastic learning environment. Playgrounds are even more powerful than what we have seen so far and we will see that as we explore deeper into the Swift language.

We are just about ready to get to the meat of learning Swift, but first let's take a moment to make sure that you can get the most out of this book.

Learning with this book


The learning process of this book follows very closely to the philosophy behind playgrounds. You will get the most out of this book if you play around with the code and ideas that we discuss. Instead of just passively reading through this, glancing at the code, put the code into a playground, and observe how it really works. Make changes to the code, try to break it, try to extend it, and you will learn far more. If you have a question, don't default to looking up the answer, try it out.

At its core, programming is a creative exercise. Yes, it requires the ability to think logically through a problem, but nine times out of ten there is no right way there is no correct answer. Technology is pushed by those of us who won't settle for the accepted solution, who aren't OK with following a fixed set of instructions, who want to push the boundaries. As we move forward in learning Swift, make this book and Swift work for you by not taking everything at face value.

Summary


We're off to a good start. We've gone over how Swift is a language designed primarily for app development, which often includes multiple different platforms. We already ran our first code and learned a little bit about how a computer runs it indirectly by first compiling it into a form it understands how to run. Most importantly, we've learned that you will learn best from this book by having a goal to work towards and by playing around with the concepts as you read along. So let's get started!

Next, we will start breaking down the basics of Swift and then put them together to make our first program.

Left arrow icon Right arrow icon

Key benefits

  • Write expressive, understandable, and maintainable Swift 2 code with this hands-on tutorial
  • Unveil the complex underpinnings of Swift to turn your app ideas into reality
  • This book is packed with real-life examples to help you implement concepts as you learn

Description

Swift is Apple’s new programming language and the future of iOS and OS X app development. It is a high-performance language that feels like a modern scripting language. On the surface, Swift is easy to jump into, but it has complex underpinnings that are critical to becoming proficient at turning an idea into reality. This book is an approachable, step-by-step introduction into programming with Swift for everyone. It begins by giving you an overview of the key features through practical examples and progresses to more advanced topics that help differentiate the proficient developers from the mediocre ones. It covers important concepts such as Variables, Optionals, Closures, Generics, and Memory Management. Mixed in with those concepts, it also helps you learn the art of programming such as maintainability, useful design patterns, and resources to further your knowledge. This all culminates in writing a basic iOS app that will get you well on your way to turning your own app ideas into reality.

What you will learn

[*] Form a solid understanding of the Swift 2 language [*] Get to know the practical aspects of how a computer program actually works [*] Understand the paradigms used by Apple's frameworks so you are not intimidated by them [*] Utilize the vast resources written in Objective-C to better inform your Swift programming [*] Develop a basic portfolio of Swift code by learning the critical concepts [*] Experience both object-oriented and functional programming [*] Get to know the new coding techniques made available by Swift 2 [*] Discover resources to ensure you never stop becoming a better developer

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Buy Now

Product Details


Publication date : Mar 23, 2016
Length 308 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781785887512
Vendor :
Apple
Category :
Languages :

Table of Contents

19 Chapters
Learning Swift Second Edition Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
Introducing Swift Chevron down icon Chevron up icon
Building Blocks – Variables, Collections, and Flow Control Chevron down icon Chevron up icon
One Piece at a Time – Types, Scopes, and Projects Chevron down icon Chevron up icon
To Be or Not To Be – Optionals Chevron down icon Chevron up icon
A Modern Paradigm – Closures and Functional Programming Chevron down icon Chevron up icon
Make Swift Work For You – Protocols and Generics Chevron down icon Chevron up icon
Everything Is Connected – Memory Management Chevron down icon Chevron up icon
Paths Less Traveled – Error Handling Chevron down icon Chevron up icon
Writing Code the Swift Way – Design Patterns and Techniques Chevron down icon Chevron up icon
Harnessing the Past – Understanding and Translating Objective-C Chevron down icon Chevron up icon
A Whole New World – Developing an App Chevron down icon Chevron up icon
What's Next? – Resources, Advice, and the Next Steps Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.