31,19 €
Start building your very own mobile apps with this comprehensive introduction to Swift and object-oriented programming
Swift Language is now more powerful than ever; it has introduced new ways to solve old problems and has gone on to become one of the fastest growing popular languages. It is now a de-facto choice for iOS developers and it powers most of the newly released and popular apps. This practical guide will help you to begin your journey with Swift programming through learning how to build iOS apps.
You will learn all about basic variables, if clauses, functions, loops, and other core concepts; then structures, classes, and inheritance will be discussed. Next, you’ll dive into developing a weather app that consumes data from the internet and presents information to the user. The final project is more complex, involving creating an Instagram like app that integrates different external libraries. The app also uses CocoaPods as its package dependency manager, to give you a cutting-edge tool to add to your skillset. By the end of the book, you will have learned how to model real-world apps in Swift.
This book is for beginners who are new to Swift or may have some preliminary knowledge of Objective-C. If you are interested in learning and mastering Swift in Apple’s ecosystem, namely mobile development, then this book is for you.
Emil Atanasov is an IT consultant who has extensive experience with mobile technologies. He started working in the field of mobile development in 2006. He runs his own contracting and consulting company, serving clients from around the world—Appose Studio Inc. He is an MSc graduate from RWTH Aachen University, Germany, and Sofia University "St. Kliment Ohridski", Bulgaria. He has been a contractor for several large companies in the US and UK, serving variously as team leader, project manager, iOS developer, and Android developer.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 341
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Ashwin NairAcquisition Editor: Reshma RamanContent Development Editor: Nikhil BorkarTechnical Editor: Madhunikita Sunil ChindarkarCopy Editor: Safis EditingProject Coordinator: Ulhas KambaliProofreader: Safis EditingIndexer: Pratik ShirodkarGraphics: Tania DuttaProduction Coordinator: Arvindkumar Gupta, Nilesh Mohite
First published: May 2018
Production reference: 1230518
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78646-392-0
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Emil Atanasov is an IT consultant who has extensive experience with mobile technologies. He started working in the field of mobile development in 2006. He runs his own contracting and consulting company, serving clients from around the world—Appose Studio Inc. He is an MSc graduate from RWTH Aachen University, Germany, and Sofia University "St. Kliment Ohridski", Bulgaria. He has been a contractor for several large companies in the US and UK, serving variously as team leader, project manager, iOS developer, and Android developer.
Giordano Scalzo is a developer with 20 years of programming experience, since the days of ZXSpectrum. He has worked in C++, Java, .Net, Ruby, Python, and in a ton of other languages that he has forgotten the names of. After years of backend development, over the past 5 years, Giordano has developed extensively for iOS, releasing more than 20 apps—apps that he wrote for clients, enterprise application, or on his own. Currently, he is a contractor in London where, he delivers code for iOS through his company, Effective Code Ltd, aiming at quality and reliability.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn Swift by Building Applications
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
Swift Basics – Variables and Functions
Variables
Optional types
Enumeration types
Basic flow statements
The if statements – how to control the code flow
Loops
The while loops
The switch statement
Functions
What is a tuple?
What is the guard statement?
How to tackle huge problems – bottom-up versus top-down
Summary
Getting Familiar with Xcode and Playgrounds
Installing Xcode
Exploring Xcode
What do we see on the screen?
Toolbar
Menu
The Navigator panel (located to the left)
The Debug panel (located at the bottom)
The Utilities panel (located to the right)
Xcode preferences window
Playground
What is a playground?
Let's add some code
How to add auxiliary code to a playground
How to add resource to a playground
Converting a playground to a workspace
Markup in playgrounds
Different items in the markup language
Basic markup items
Summary
Creating a Minimal Mobile App
Your first iOS application
Project structure
AppDelegate
Application states
ViewController
Git
Summary
Structures, Classes, and Inheritance
Structures and classes
Extensions
The deinit method
Type properties and functions
Adding custom data types to a playground
Inheritance
Base class
Class properties
Model-View-Controller (MVC)
Summary
Adding Interactivity to Your First App
Storyboards
Visual components
Adding items to the storyboard
Linking the UI with the code
General discussion
Summary
How to Use Data Structures, OOP, and Protocols
Primary collection types
Generics
Array
Set
Dictionary
How to choose the best collection type
List of items in a playground
UICollectionView
UICollectionViewCell
Reusing cells
Layouts
Table view in iOS app
Model list of cities
Displaying all cities
Adding search
Protocols
Protocols and inheritance
Summary
Developing a Simple Weather App
Defining the app screens
The home screen
Favorite locations
Constraints
Picking a location
Model
Locations
Controllers and segues
The first segue
How to pass data
Passing information in the reverse direction
Defining a custom segue
Further improvements
Summary
Introducing CocoaPods and Project Dependencies
Software – the modern way
Ruby and CocoaPods
How to use it
CocoaPods useful commands
Carthage
Swift Package Manager 
Useful commands
Popular third-party libraries
Alamofire
Texture
RxSwift
Summary
Improving a Version of a Weather App
Weather forecast API
What's an API?
List of requests
Creating new models
Pure network requests
Alamofire implementation
Improvements using third-party libraries
Better error handling
About the screen
Summary
Building an Instagram-Like App
Tabbed app project
Firebase
Login
The different screens
Custom buttons on the tab bar
Creating a post
Models
Firebase
Filters
Summary
Instagram-Like App Continued
Home screen
Profile screen
Search screen
Favorites screen
Polishing the home screen
Summary 
Contributing to an Open Source Project
Your account at GitHub
Forking a repository
Let's contribute
Pull request
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
Learning Swift 4 by Building Applications is a book that teaches the basics of Swift in the context of iOS. If you finish the book, you should be able to develop small-to-medium mobile apps. You will know how to create the app UI in storyboard using Xcode, how to load and display images fetched from the cloud, how to save and load information between different sessions of the app, and how to share data between all users of the app using the cloud.
The book is designed for beginners who have little or no experience with Swift or any other programming language. The first couple of chapters introduce the Swift and the core programming principals, which are used throughout the process of software development. The rest of the book discusses the Swift development of iOS mobile applications. We will explain how to use open source libraries to achieve rapid software development and develop apps that are consuming information and images from the cloud.
Chapter 1, Swift Basics – Variables and Functions, discusses the basics of the Swift language, starting from the A, B, and C.
Chapter 2, Getting Familiar with Xcode and Playgrounds, presents the Xcode—a free IDE that we will use when developing Swift. We shouldn't forget that Xcode is developed by Apple and that the playgrounds are the perfect place for learning Swift step by step.
Chapter 3, Creating a Minimal Mobile App, makes you examine the minimal mobile app and its structure. This is the basis of every iOS mobile app written in Swift.
Chapter 4, Structures, Classes, and Inheritance, covers the benefit of different data structures and how easily we can model a real-world problems.
Chapter 5, Adding Interactivity to Your First App, looks at the different ways to add interactivity to an app or how to interact with the user in the app.
Chapter 6, How to Use Data Structures, OOP, and Protocols, explores the data structures and different techniques to incorporate them in our solutions.
Chapter 7, Developing a Simple Weather App, focuses on how to build a real mobile app starting from the UI and displaying static data.
Chapter 8, Introducing CocoaPods and Project Dependencies, introduces the modern way of rapid development using various dependency managers of Swift libraries.
Chapter 9, Improving a Version of a Weather App, discusses about consuming information from the public API and displaying it in our Weather app.
Chapter 10, Building an Instagram-Like App, builds an app from the idea step by step starting with the design, defines the basic UI, and connects it with a real cloud service provider—Firebase.
Chapter 11, Instagram-Like App Continued, makes the app complete and functional so that it can look like a working product, ready to be shared with users.
Chapter 12, Contributing to an Open Source Project, takes you through the basics of contributing to an open source project.
You have to know what is a computer and have basic knowledge of how to use a Mac. You have to be curious about how things work. We will start from the basics of the Swift programming language and Xcode. Most of the book is related to iOS, and it would be nice to have an iOS device to see your mobile applications working on a real device.
You need enough time and patience to go through the book and to experiment with the code, which can be found on GitHub.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
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
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-Swift-by-Building-Applications. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it from http://www.packtpub.com/sites/default/files/downloads/LearnSwiftbyBuildingApplications_ColorImages.pdf.
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, we will present the basics of the Swift language, starting from square one: introducing the basic concepts. The code, which is part of the chapter, illustrates the topics under discussion. In the next chapter, we will learn how to execute code samples in Xcode.
Let's begin with a brief history of Swift. This is a brand new programming language, developed by Apple and announced in 2014. In 2016, Swift 3 was released as open source, and this is the first major version, which enables people interested in Swift to develop the language. This means only one thing: Swift will start spreading even faster, beyond Apple's ecosystem. In this book, we will give examples of Swift, and we will discuss most of our solutions related to iOS, but you should know that the knowledge here is applicable across all places where Swift code is used.
Before diving into real code, let's define some basic concepts that we can use later in the book.
What is a computer program or application (app)? Simply, we can think of an app as a set of computer instructions that can be executed. Each app has a source code, written in a language describing all actions that the program does. In our case, we will write mobile (iOS) apps in Swift.
There are many low-level computer instructions, but Swift helps us to write without hassle, without knowing much about the low-level organization. Now we will start with the basic concept of variables.
We will discuss the following topics:
Constants and variables
Initializing using expressions
Basic types in Swift
Optional types
Enumeration types
Code flow statements –
if
,
switch
, loops
Functions
Tuples
The
guard
statement
Top-down and bottom-up
We begin with the basic building blocks of all programs.
What are basic flow statements? These are several statements which help you to structure the program code in a way that allows you to do different action(s) based on the data stored in particular variables. We will learn how to execute just part of the code if a certain condition is met (the condition could be a pretty complex Boolean expression). Then, we will find a way to execute different actions several times in a loop. The next thing will be to learn how to repeat things until a condition is met and to stop executing statements once the condition is not satisfied. Using flow-control statements, we can construct pretty complex code chunks, similar to what we can express with regular text writing. To develop a program, we should first create an algorithm (a sequence of steps) which leads to the desired result, taking into account all external and internal conditions. Based on this sequence, we can then develop a program, using all flow operators. But let's get familiar with some forms of them.
A switch statement is a concise way to describe a situation where we have several possible options to pick from and we don't want to write a lot of boilerplate code using the already familiar if statement.
Here is the general pattern of a switch statement (please note that this is not a valid Swift code):
switch a-variable-to-be-matched { case value-1: //code which will be executed, if variable has value-1 //we need at least one valid executable statement here (comments are not an executable statement) case value-2, value-3: //code which will be executed, if variable has value-2 or value-3 default: //code which will be executed, if variable has value different from all listed cases }
What we see is that switch has many possible cases, each one starting with the special word case, and then a specific value. Swift supports specific value matching, but it supports more complex rules for pattern matching. Each case could be considered as a separate if statement. If one case is activated, then all others are skipped. The default case is a specific one and is triggered if there is no match with any other case. The default case appears at the end, and it's defined with the special word default.
We can use break to interrupt execution of the code in a case statement. If we want to have an empty case statement, it's good to add break.
We have some specifics with the implementation of switch in Swift, which are new when compared to the other programming languages, but they improve the readability of the code. First, there is now a way to have an empty body of a specific case. To be correct, we have to add at least one valid statement after the case. There is no implicit fallthrough after each case. This means that once the last executable statement in a case branch is triggered, we are continuing after the switch statement. Nothing else that is part of the switch statement will be executed. We could consider that every case statement has a hidden break at its very end. Next, we need the special word fallthrough