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
Free Learning
Arrow right icon
Learning Swift
Learning Swift

Learning Swift: Build a solid foundation in Swift to develop smart and robust iOS and OS X applications

eBook
$27.98 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Learning Swift

Chapter 1. Introducing Swift

A programming language is really only ever a means to an end, and you are not going to learn much from this book or any other resource if you don't have at least some idea of what that end is. Before diving into learning Swift, we have to understand what it really is and how it will help us achieve 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 this, we will go over the following topics:

  • 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 to allow developers to continue pushing their platforms forward. It is their attempt to make iOS and OS X app development more modern, safe, and powerful.

Developers have already begun looking for ways to push Swift to do even more than iOS and OS X app development. Some are using it to create command-line scripts to replace/supplement the existing scripting languages, such as Python and Ruby. However, Apple's priority, at least for now, is to make it the best language possible to facilitate app development.

It is important to note that learning Swift is only the first step towards developing Apple's platforms. To develop a device, you must learn the programming language and the frameworks that the device maker provides. Skill in a programming language is the foundation to get 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, first, you need to step away from the table and focus on developing your skill set. The better you are at using the tools, the more possibilities open up to you to create more advanced and high quality furniture. Similarly, with 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 language-related skill set. 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 wouldn'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 with Swift. To do this, we will introduce the syntax and features of Swift in a practical way. You will build up a rich toolset, and see it being 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 have a Mac running OS X. The only piece of software you will need is called Xcode (version 6 and higher). This is the environment that Apple provides to facilitate 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.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased 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.

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 here:

Running our first Swift code

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

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

Running our first Swift code

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 along the right-hand side of the sidebar.

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 to add extra information about your code there inline with it. In Swift there are two types of comments: single line and multiline. Single line comments such as the one in the previous code always start with //. 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
*/

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 the last 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 be updated, 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.

Another 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 Swift code is completely valid. 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 are shown the full error:

Running our first Swift code

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

Running our first Swift code

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

Understanding playgrounds

A playground is not actually 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 itself a program and it is one way to define a programming language.

The Swift compiler accepts Swift code as input, and if it can properly parse and understand the code, it 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 what we are trying to learn when we say we are learning Swift.

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

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 have to perform 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 want 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 develop 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 this as we delve 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 ensure that you can get the most out of this book.

Learning with this book

The learning process for 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 and 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 or extend it, and you will learn far more. If you have a question, try it out before looking up the answer.

At its core, programming is a creative exercise. Yes, it requires the ability to think logically through a problem, but 9 times out of 10 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 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 for app development and we already ran our first code. We learned a little bit about how a computer runs our Swift code indirectly by first compiling it into a form it understands. 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!

Left arrow icon Right arrow icon

Description

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.

Who is this book for?

If you are looking to build iOS or OS X apps using the most modern technology, this book is ideal for you. You will find this book especially useful if you are new to programming or if you have yet to develop for iOS or OS X.
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 30, 2015
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392505
Vendor :
Apple
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Taiwan

Standard delivery 10 - 13 business days

$12.95

Premium delivery 5 - 8 business days

$45.95
(Includes tracking information)

Product Details

Publication date : Jun 30, 2015
Length: 266 pages
Edition : 1st
Language : English
ISBN-13 : 9781784392505
Vendor :
Apple
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 147.97
Mastering Swift
$54.99
Learning Swift
$48.99
Swift By Example
$43.99
Total $ 147.97 Stars icon
Banner background image

Table of Contents

12 Chapters
1. Introducing Swift Chevron down icon Chevron up icon
2. Building Blocks – Variables, Collections, and Flow Control Chevron down icon Chevron up icon
3. One Piece at a Time – Types, Scopes, and Projects Chevron down icon Chevron up icon
4. To Be or Not to Be – Optionals Chevron down icon Chevron up icon
5. A Modern Paradigm – Closures and Functional Programming Chevron down icon Chevron up icon
6. Make Swift Work for You – Protocols and Generics Chevron down icon Chevron up icon
7. Everything is Connected – Memory Management Chevron down icon Chevron up icon
8. Writing Code the Swift Way – Design Patterns and Techniques Chevron down icon Chevron up icon
9. Harnessing the Past – Understanding and Translating Objective-C Chevron down icon Chevron up icon
10. A Whole New World – Developing an App Chevron down icon Chevron up icon
11. What's Next? Resources, Advice, and Next Steps Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.8
(5 Ratings)
5 star 80%
4 star 20%
3 star 0%
2 star 0%
1 star 0%
Ronnie Pitman Aug 16, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is not a huge, thick book, but it is a book packed with information. In the Preface it is written that this book is “especially useful if you are new to programming or….” While it’s true that Chapter 2 does start with the basics—variables, constants, tuples, arrays, dictionaries, etc.—the material moves on quickly. All concepts, throughout the book, are amply demonstrated in Playgrounds, but still, someone new to programming will have to pay close attention and probably reread portions. In at least two chapter summaries, the author himself refers to the material presented as having been dense. It’s good to have a book that deals in depth.Many programming books teach Swift in the context of iOS. This one does not but instead concentrates on Swift language fundamentals. It’s not a tutorial on how to build this or that app, and only in the penultimate chapter does the author address iOS and building an app.Many programming books also jam a great deal of code into one class. This author places a premium on code reuse and flexibility and writes his code accordingly.A note on the book’s code files: at the time I write this, if you download them from the publisher website they download as Learning Swift.zip.html. Unless Packt knows something I don’t know, you have to strip .html off the file name for it to open as a zip file rather than as gibberish.A small error in Chapter 2 (pdf page 13): “View | Assistant Editor | Assistant Editor” should be “View | Assistant Editor | Show Assistant Editor”. Otherwise this book is admirably edited and proofread.
Amazon Verified review Amazon
Aurélien Sep 02, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
What this book is not:This book is not a Bible, it does not deal with countless topics, it is not either a how-to guide to programming your first Iphone app. "Learning Swift" is not packed with information easily googled and deprecated within the next 6 months.What it is:Instead "Learning Swift" focuses on how to understand Swift programming, how the language is structured and how it works.It gives the keys to become a good swift developper by understanding the core concepts, while being concrete at every step of the process.A whole chapter is dedicated to Design Patterns, and even chapter 10 "Developing an App" is full of good advices on how to code properly and how to refactor your code.
Amazon Verified review Amazon
Winston Sep 05, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The author does a great job of taking the reader through all the intricacies of the swift programing language. Apple is now in Swift 2 and this book will put any novice or experienced developer in the drivers seat to building award winning ios apps. Buy it!
Amazon Verified review Amazon
Sergio Martinez-Losa del Rincon Aug 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a very nice one to learn swift from scratch, it is useful information from easy topic to difficult ones, you can learn many useful thinks like categories, interpolation, infix/postfix, optionals...Patterns chapter is very handy, because you can reuse your programming techniques to create a more easy code. Also I found very useful optionals information.I learn a lot with this book, it deserves a 5-stars.
Amazon Verified review Amazon
Michael Aug 28, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I am new to learning Mac and iOS programming. This book is great even though I've only gotten through a couple chapters. It starts out with the basics of types, collections, conditionals and loops and builds on that.One note, this book was written for XCode 6 and Swift 1.2 so it will hopefully be updated for XCode 7 and Swift 2 when they are released since some of the basic functions are changing, for example the println() function is replaced by print(). The beta for XCode 7 does have functionality to convert the 1.2 to 2.0 code. Hopefully that will be in the final build of XCode 7.I look forward to getting deeper into learning Swift.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact [email protected] with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at [email protected] using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on [email protected] with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on [email protected] within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on [email protected] who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on [email protected] within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela