iOS Programming Cookbook: Over 50 exciting and powerful recipes to help you unearth the promise of iOS programming
()
About this ebook
Do you want to understand all the facets of iOS programming and build complex iOS apps? Then you have come to the right place. This problem-solution guide will help you to eliminate expensive learning curves and focus on specific issues to make you proficient at tasks and the speed-up time involved.
Beginning with some advanced UI components such as Stack Views and UICollectionView, you will gradually move on to building an interface efficiently.
You will work through adding gesture recognizer and touch elements on table cells for custom actions. You will work with the Photos framework to access and manipulate photos. You will then prepare your app for multitasking and write responsive and highly efficient apps. Next, you will integrate maps and core location services while making your app more secure through various encryption methods. Finally, you will dive deep into the advanced techniques of implementing notifications while working with memory management and optimizing the performance of your apps. By the end of the book, you will master most of the latest iOS 10 frameworks.
Related to iOS Programming Cookbook
Related ebooks
iOS Programming Cookbook Rating: 0 out of 5 stars0 ratingsLearning Android Game Development: A Beginner's guide to developing popular Android games Rating: 0 out of 5 stars0 ratingsiOS Game Programming Cookbook Rating: 0 out of 5 stars0 ratingsMastering Android Game Development with Unity Rating: 0 out of 5 stars0 ratingsUnity 2018 Shaders and Effects Cookbook: Transform your game into a visually stunning masterpiece with over 70 recipes, 3rd Edition Rating: 0 out of 5 stars0 ratingsAndroid 9 Development Cookbook: Over 100 recipes and solutions to solve the most common problems faced by Android developers Rating: 0 out of 5 stars0 ratingsECMAScript Cookbook: Over 70 recipes to help you learn the new ECMAScript (ES6/ES8) features and solve common JavaScript problems Rating: 0 out of 5 stars0 ratingsUnreal Engine 4 Shaders and Effects Cookbook: Over 70 recipes for mastering post-processing effects and advanced shading techniques Rating: 0 out of 5 stars0 ratingsLearning Microsoft Cognitive Services - Second Edition: Leverage Machine Learning APIs to build smart applications Rating: 0 out of 5 stars0 ratingsMEAN Cookbook: The meanest set of MEAN stack solutions around Rating: 0 out of 5 stars0 ratingsPractical Game AI Programming: Unleash the power of Artificial Intelligence to your game Rating: 0 out of 5 stars0 ratingsReact Material-UI Cookbook: Build captivating user experiences using React and Material-UI Rating: 0 out of 5 stars0 ratingsC# 7 and .NET Core Cookbook Rating: 0 out of 5 stars0 ratingsMastering iOS 11 Programming - Second Edition: Build professional-grade iOS applications with Swift 4 and Xcode 9 Rating: 0 out of 5 stars0 ratingsGo Standard Library Cookbook: Over 120 specific ways to make full use of the standard library components in Golang Rating: 0 out of 5 stars0 ratingsVue.js 2 Cookbook Rating: 0 out of 5 stars0 ratingsMastering Android Development with Kotlin: Deep dive into the world of Android to create robust applications with Kotlin Rating: 0 out of 5 stars0 ratingsMastering Firebase for Android Development: Build real-time, scalable, and cloud-enabled Android apps with Firebase Rating: 0 out of 5 stars0 ratingsVue.js 2.x by Example: Example-driven guide to build web apps with Vue.js for beginners Rating: 0 out of 5 stars0 ratingsSwift 4 Programming Cookbook Rating: 0 out of 5 stars0 ratingsMatplotlib 3.0 Cookbook: Over 150 recipes to create highly detailed interactive visualizations using Python Rating: 0 out of 5 stars0 ratingsGame Audio Development with Unity 5.X Rating: 0 out of 5 stars0 ratingsSwift Functional Programming - Second Edition Rating: 3 out of 5 stars3/5HoloLens Blueprints Rating: 0 out of 5 stars0 ratingsModern C++ Programming Cookbook Rating: 5 out of 5 stars5/5Windows Presentation Foundation Development Cookbook: 100 recipes to build rich desktop client applications on Windows Rating: 0 out of 5 stars0 ratingsFun Games with Scratch 3.0: Learn to Design High Performance, Interactive Games in Scratch (English Edition) Rating: 0 out of 5 stars0 ratingsHaskell Cookbook Rating: 0 out of 5 stars0 ratings
Operating Systems For You
Learn SQL Server Administration in a Month of Lunches Rating: 3 out of 5 stars3/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Windows 11 All-in-One For Dummies Rating: 5 out of 5 stars5/5Hacking : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Ethical Hacking Rating: 5 out of 5 stars5/5The Windows Command Line Beginner's Guide: Second Edition Rating: 4 out of 5 stars4/5Make Your PC Stable and Fast: What Microsoft Forgot to Tell You Rating: 4 out of 5 stars4/5Hacking for Beginners: Mastery Guide to Learn and Practice the Basics of Computer and Cyber Security Rating: 0 out of 5 stars0 ratingsBash Command Line Pro Tips Rating: 5 out of 5 stars5/5Exploring Windows 11: The Illustrated, Practical Guide to Using Microsoft Windows Rating: 0 out of 5 stars0 ratingsiPhone For Dummies Rating: 0 out of 5 stars0 ratingsPowerShell: A Beginner's Guide to Windows PowerShell Rating: 4 out of 5 stars4/5Linux All-In-One For Dummies Rating: 2 out of 5 stars2/5The Mac Terminal Reference and Scripting Primer Rating: 4 out of 5 stars4/5OneNote: The Ultimate Guide on How to Use Microsoft OneNote for Getting Things Done Rating: 1 out of 5 stars1/5macOS Sonoma For Dummies Rating: 0 out of 5 stars0 ratingsMac Unlocked: Everything You Need to Know to Get Cracking in macOS Big Sur Rating: 0 out of 5 stars0 ratingsiPhone Unlocked Rating: 0 out of 5 stars0 ratingsRaspberry Pi Cookbook for Python Programmers Rating: 0 out of 5 stars0 ratingsHelp! iOS 17 - iPhone: How to Use iOS17 Rating: 0 out of 5 stars0 ratingsRHCSA Red Hat Enterprise Linux 8 (UPDATED): Training and Exam Preparation Guide (EX200), Second Edition Rating: 5 out of 5 stars5/5The Darknet Superpack Rating: 0 out of 5 stars0 ratingsThe Linux Command Line Beginner's Guide Rating: 4 out of 5 stars4/5Shell Scripting: Expert Recipes for Linux, Bash, and more Rating: 0 out of 5 stars0 ratingsEasy Linux For Beginners Rating: 2 out of 5 stars2/5Linux Bible Rating: 0 out of 5 stars0 ratingsUbuntu Linux Toolbox: 1000+ Commands for Power Users Rating: 3 out of 5 stars3/5
Reviews for iOS Programming Cookbook
0 ratings0 reviews
Book preview
iOS Programming Cookbook - Hossam Ghareeb
iOS Programming Cookbook
Over 50 exciting and powerful recipes to help you unearth the promise of iOS programming
Hossam Ghareeb
BIRMINGHAM - MUMBAI
iOS Programming Cookbook
Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.
First published: March 2017
Production reference: 2310317
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78646-098-1
www.packtpub.com
Credits
About the Author
Hossam Ghareeb is a software engineer who graduated from Alexandria University in 2012. He found his passion in mobile development, especially iOS development. Currently, he is a senior iOS developer at Noon e-commerce in Dubai.
Hossam has built his experience by learning tips and tricks from the managers he works with, open source projects, and online tutorials. He discovered that the best way to pay this back is to share his experience with others and help people get experience in iOS development.
First of all, big thanks to my parents whom I owe for everything I have and the good things that they taught me. I would like to thank my wife for her support and encouragement to keep writing the book. I want to thank my son Yusuf for inspiring me despite of all the time this took me away from him. Thanks to all the mentors that I've met over the years. Last but not least, special thanks to Samantha Gonsalves, the content editor of the book, for her cooperation and support in completing the book and to the reviewers for their comments and suggestions.
About the Reviewer
Siddharth Shekar is a game developer with over 5 years of industry experience in game development, 11 years of experience in C++, C#, and other programming languages, and is adept at graphics libraries and game engines such as Unity and Unreal. He has also published games on the iOS, Android, Amazon, and Windows Phone App Stores.
Siddharth is also the author of Learning Cocos2d-x Game Development, Learning iOS 8 Game Development Using Swift, and Cocos2d Cross-Platform Game Development Cookbook, all published by Packt Publishing.
Currently, he is a lecturer in the Games Department at Media Design School, Auckland, New Zealand. He teaches graphics programming and PlayStation 4/PS Vita native game development and mentors final year production students.
More information about Media Design School and Siddharth Shekar can be found at www.mediadesignschool.com.
I would like to thank my parents for supporting me in everything that I choose to do. I would also like to thank Media Design School for encouraging me to continue working on this book. Finally, I would like to thank Packt Publishing for putting this book together and offering me the opportunity to review the book.
www.PacktPub.com
For support files and downloads related to your book, please visit www.PacktPub.com.
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.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Customer Feedback
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/178646098X.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Table of Contents
Preface
What this book covers
What you need for this book
Who this book is for
Sections
Getting ready
How to do it...
How it works...
There's more...
See also
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Swift Programming Language
Introduction
Using closures to create self-contained code
Getting ready
How to do it...
How it works...
There's more...
Inferring type
Omitting the return keyword
Shorthand arguments
Creating enumerations to write readable code
Getting ready
How to do it...
How it works...
There's more...
Enum raw values
Assigning raw values
Using Enums with raw values
Enums with associated values
Working with protocols and delegates
Getting ready
How to do it...
How it works...
There's more...
Mutating methods
Delegation
Class-only protocols
Checking protocol conformance
Optional requirements
Using extensions to extend classes functionality
Getting ready
How to do it...
How it works...
There's more...
Mutating instance methods
Adding new initializer
Define subscripts
Working with memory management and ARC
Getting ready
How to do it...
How it works...
There's more...
Using error handling
Getting ready
How to do it...
How it works...
There's more...
Multiple catch statements
Disable error propagation
Using generics to write generic and reusable code
Getting ready
How to do it...
How it works...
The Essentials
Introduction
Using UIView via code or interface builder to build your own custom views
Getting ready
How to do it...
How it works...
There's more...
Working with navigation controller and navigation bar
Getting ready
How to do it...
How it works...
There's more...
Push and pop
Hiding navigation bar
Navigation bar color
Working with stack views
How to do it
How it works...
Working with UICollectionView
How to do it...
How it works...
There's more...
Customizable layouts
Working with gestures like swipe, pan, rotation, and tap
Getting ready
How to do it...
How it works...
There's more...
Using 3D touch
How to do it...
How it works...
There's more...
Home screen quick actions
Integrating with Messages App
Introduction
Integrating iMessage app with sticker pack
Getting ready
Stickers
How to do it...
How it works...
There's more...
Integrating iMessage app with iMessage app
Getting ready
How to do it...
How it works...
There's more...
Showing progress indicator
Request files with pagination
Working with Interface Builder
Introduction
Using storyboards
Getting ready
How to do it...
How it works...
There's more...
Segues attributes
Preparing for a segue
Unwind segues (exit segues)
Custom segues
Working with Autolayout and constraints
Getting ready
How to do it...
How it works...
There's more...
Updating constraints
Designing your interface builder for any size classes in one storyboard
Getting ready
How to do it...
How it works...
Embedding view controllers using container view
How to do it...
How it works...
There's more...
Working with UITableView
Introduction
Working with scroll view
Getting ready
How to do it...
How it works...
There's more...
Using TableView sections, headers and footers
Getting ready
How to do it...
How it works...
There's more...
Custom section header and footer
Using custom cells
Getting ready
How to do it...
How it works...
Resizing table view cells dynamically
How to do it...
How it works...
Editing table views
Getting ready
How to do it...
Inserting cells with animation
Removing cells with animation
Dragging and dropping to reorder cells
How it works...
There's more...
Animations and Graphics
Introduction
Drawing text, images, lines, rectangles, and gradients
Getting ready
How to do it...
How it works...
There's more...
Animating shapes drawn with UIBezierPath
Getting ready
How to do it...
How it works...
Animating UIViews
How to do it...
How it works...
Multimedia
Introduction
Working with audio capabilities
Getting ready
How to do it...
How it works...
There's more...
Recognizing speech
Playing videos
Getting ready
How to do it...
How it works...
There's more...
Slide Over
Split View
Picture-in-Picture
Capturing photos and videos
How to do it...
How it works...
Using filters with CoreImage
How to do it...
How it works...
Concurrency
Introduction
Using Dispatch queues
Getting ready
How to do it...
How it works...
There's more...
Using Operation queues
Getting ready
How to do it...
How it works...
Using Operation subclassing
How to do it...
How it works...
Location Services
Introduction
Detecting user location
How to do it...
How it works...
Displaying pins in map view
Getting ready
How to do it...
How it works...
Getting directions between locations
How to do it...
How it works...
Working with geofencing
How to do it...
How it works...
Security and Encryption
Introduction
Using Touch ID for user authentication
Getting ready
How to do it...
How it works...
Working with Keychain
Getting ready
How to do it...
How it works...
Encryption
Getting ready
How to do it...
How it works...
Networking
Introduction
Using NSURLSession API for network connections
Getting ready
How to do it...
How it works...
Parsing JSON data
Getting ready
How to do it...
How it works...
Social sharing
Getting ready
How to do it...
How it works...
Persisting Data with Core Data
Introduction
Designing data models
How to do it...
How it works...
Reading and inserting records to Core Data
How to do it...
How it works...
Updating and deleting records from Core Data
How to do it...
How it works...
Notifications
Introduction
Setting up Push Notifications
Getting ready
How to do it...
How it works...
Setting up a local server to send Push Notifications
Getting ready
How to do it...
How it works...
Working with interactive Push Notifications
How to do it...
How it works...
Working with local notifications
How to do it...
How it works...
App Search
Introduction
App indexing using NSUserActivity
Getting ready
How to do it...
How it works...
There's more...
App indexing using Core Spotlight APIs
How to do it...
How it works...
Optimizing Performance
Introduction
Memory management with ARC
Getting ready
Retain cycles
Working with closures
How to do it...
How it works...
Measuring performance
How to do it...
How it works...
Measuring energy impact
How to do it...
How it works...
On-demand resources
Getting ready
How to do it...
How it works...
Preface
iOS is evolving every year to provide a better experience for its users. Not only the system, but also the hardware of iPhone and iPad devices, which require a powerful system like the iOS to utilize the features of hardware is evolving. The latest release of iOS now comes with great features to give iOS developers the chance to develop mobile apps with new ideas or enhance the experience of current apps with new features. The book tries to cover the new features of iOS and let iOS developers get their hands dirty by writing sample demos with the features to understand how they work. The book is not meant to be a theory book, which talks about technical things, such as new APIs, or about any specific topic. The book is a cookbook that takes you within minutes to the point and guides you to build a simple demo to understand what is going on using examples, which is the best way to make things stick in your mind.
What this book covers
Chapter 1, Swift Programming Language, is a simple revision of Swift 3 and an explanation of the most important topics in Swift.
Chapter 2, The Essentials, covers the most commonly used UI components, such as UIView, gestures, stack views, and so on.
Chapter 3, Integrating with Messages App, talks about one of the hottest features in iOS--how to integrate with the iOS Messages app to add your own stickers or develop extensions.
Chapter 4, Working with Interface Builder, provides tips and tricks while dealing with interface builders, such as storyboards and XIB files. Get your hands dirty with Autolayout and size classes and know how to work with them.
Chapter 5, Working with UITableView, covers one of the most important components in iOS that all iOS developers should be aware of.
Chapter 6, Animations and Graphics, gives your apps a better look by teaching you how to animate views and draw simple shapes.
Chapter 7, Multimedia, helps you to deal with audio and video in iOS. It provides information about how to use filters thanks to the Core Image framework.
Chapter 8, Concurrency, overcomes the fear of using concurrency in iOS by helping you understand how to use dispatch queues and NSOperationQueues with simple examples.
Chapter 9, Location Services, covers the most commonly used operations in location services, such as getting a user's location, adding pins, navigation, and geofencing.
Chapter 10, Security and Encryption, discusses how to secure your app and protect your user's sensitive information using Touch ID for authentication and saving data in a device's Keychain.
Chapter 11, Networking, covers how to establish networking in an iOS app to retrieve data and parse it.
Chapter 12, Persisting Data with Core Data, takes you through the workings of Core Data to persist data and perform CRUD (creation, reading, updating, and deletion) operations.
Chapter 13, Notifications, helps you overcome the hassle of dealing with push notification and setup and gets you started with configuring your project and server to send and receive notifications.
Chapter 14, App Search, looks at making your app content searchable from Spotlight and Safari suggestions.
Chapter 15, Optimizing Performance, showcases how to measure the performance of your app and how to enhance it.
What you need for this book
Any Mac hardware-running macOS system, such as MacBook Pro, MacBook Air, Mac Mini, iMac, or Mac Pro.
Some chapters require testing on an iOS device with iOS 10.0 or later version.
The software requirements are Xcode 8.1 or later, which requires a Mac running macOS 10.11.5 or later, and iOS Simulator 10.0 or later.
Who this book is for
If you are an iOS developer on a quest to develop your perfect iOS app, then this book is for you. It would also prove to be a valuable resource for those who want to get up and running with iOS development through a clear, practical approach. In order to unleash the full potential of this book, basic Swift programming knowledge is necessary.
Sections
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
Getting ready
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
How to do it...
This section contains the steps required to follow the recipe.
How it works...
This section usually consists of a detailed explanation of what happened in the previous section.
There's more...
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
See also
This section provides helpful links to other useful information for the recipe.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: The sort function gives us another flexibility by which you can provide a closure that returns the comparison result between any two items in the list to determine which should come first in the list.
A block of code is set as follows:
{ (parameters) ->returnType in
// block of code goes here
}
Any command-line input or output is written as follows:
cd path_to_directory
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: Under Relationship Segue, click on view controllers to make this view controller part of the view controllers list on the tab bar controller.
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
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.
You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.
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/iOS-Programming-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Downloading the color images of this book
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/iOSProgrammingCookbook_ColorImages.pdf.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
Swift Programming Language
In this chapter, we will cover the following topics:
Using closures to create self-contained code
Creating enumerations to write readable code
Working with protocols and delegates
Using extensions to extend classes functionality
Working with memory management and ARC
Using error handling
Using generics to write generic and reusable code
Introduction
Welcome to our first chapter in iOS Programming Cookbook. We will start our journey in this book with a revision or emphasize on the most important and commonly used topics in Swift programming language. Before talking about these topics, ensure that you have a basic knowledge about Swift programming language and have used it before.
It has been more than 2 years since Apple released the awesome programming language-Swift. Swift is meant to be easy to code, easy to learn, safe, and intuitive. For each version of Swift, Apple introduces some awesome features and enhancements in the language. As we see in Swift 2.0, Swift came with higher performance, and new APIs such as error handling, and some enhancements. Swift is not meant to be available in iOS development only; you may find it in other platforms later in the future, thanks to the announcement of Apple that Swift will become open source.
Our recipes in this chapter will focus on the most important topics in Swift that will be used frequently in iOS development. When you focus on these topics and learn them properly, you will find using them in development will make your life easier and your code will be more organized. There are many people who can write code, but only few can write awesome code. Thus, mastering these topics is very important to be a good developer and to help you and others working on a project.
For the latest features of Swift, ensure that you are using the latest version of Xcode.
Using closures to create self-contained code
Closures are self-contained lines of code to be executed and passed like any other data types. You should be familiar with blocks or at least heard about them in Objective-C or C. This recipe will help you to understand closure syntax and get familiar in using them.
Getting ready
Closures syntax in Swift is pretty easy and is easier than the syntax in C or Objective-C. The general form of closure is as follows:
{ (parameters) ->returnType in
// block of code goes here
}
As you see, you first put open curly braces, add list of parameters and the return type, then the keyword in, followed by lines of code in your closure. Closures are first-class type, which means it can be nested, passed in parameters, returned from function, and so on.
How to do it...
Go to Xcode and create a new playground file called Closures to test code about closures in it.
To see closures in action, copy and paste this piece of code in the playground file (the output of each statement is printed on the right):
var names = [David
, Jones
, Suzan
, Naomi
, Adam
]
names.sort() // [Adam
, David
, Jones
, Naomi
, Suzan
]
names.sort{ (str1: String, str2: String) ->Bool in
return str1 > str2
}
// [Suzan
, Naomi
, Jones
, David
, Adam
]
How it works...
Swift provides us with a built-in system function called sort. The function can sort any collection of data. The function, by default, will sort the collection in an ascending order. The sort function gives us another flexibility by which you can provide a closure that returns the comparison result between any two items in the list to determine which should come first in the list.
As we saw, the default sort function sorts our data in an ascending order; in order to do any other logic, we can sort with closure that gives you two items as parameters to decide how to compare them. The sort function sorts the collection in place, and that's why the names variable is created as var not let. If the names collection is defined as let, you will not be able to use the sort() function. There is another function called sorted(), which returns a totally new sorted collection without changing the original one. It's available in both versions of the collection with var or let.
There's more...
Even though the closure syntax looks simple, but Swift can make it simpler. Let's see how closure syntax can be optimized.
Inferring type
When closures are passed as argument like what we did in the sort function, Swift can infer the types of closure parameters and return type. In that case, we can omit the parameters and return types, as there is no need to write them. In our previous example, when we infer types, the sort function would be like this:
names.sort{ str1, str2 in
return str1 > str2
}
As you can see, the String types and the return type have been omitted.
Omitting the return keyword
Swift can make your life easier than that. When closure body consists of only one expression, the return keyword can be omitted. So, the new version of sort function will be like this:
names.sort({ str1, str2 in str1 > str2})
Shorthand arguments
To reach the maximum awesomeness of Swift, you can refer to the argument list with names $0, $1, and so on. When you decide to use the shorthand arguments, you can omit the list of parameters. You may ask what about the in keyword, will it be alone? The answer is no, we won't leave it alone; we can omit it as well completely. Here is the final version of our sort function:
names.sort({ $0 > $1})
Creating enumerations to write readable code
Using enumerations is one of the best practices that you should follow while writing any software project and not only iOS projects. Once you find that you have a group of related values in your project, create enum to group these values and to define a safe type for these values. With enumerations, your code becomes more readable and easy to understand, as it makes you define new types in your project that map to other value. In Swift, enumerations have been taken care of and have become more flexible than the ones used in other programming languages.
Getting ready
Now, we will dive into enumerations and get our hands dirty with it. To do so, we will create a new playground file in Xcode called Enumerations so that we can