Book Image

Hands-On Design Patterns with Swift

By : Florent Vilmart, Giordano Scalzo, Sergio De Simone
Book Image

Hands-On Design Patterns with Swift

By: Florent Vilmart, Giordano Scalzo, Sergio De Simone

Overview of this book

Swift keeps gaining traction not only amongst Apple developers but also as a server-side language. This book demonstrates how to apply design patterns and best practices in real-life situations, whether that's for new or already existing projects. You’ll begin with a quick refresher on Swift, the compiler, the standard library, and the foundation, followed by the Cocoa design patterns – the ones at the core of many cocoa libraries – to follow up with the creational, structural, and behavioral patterns as defined by the GoF. You'll get acquainted with application architecture, as well as the most popular architectural design patterns, such as MVC and MVVM, and learn to use them in the context of Swift. In addition, you’ll walk through dependency injection and functional reactive programming. Special emphasis will be given to techniques to handle concurrency, including callbacks, futures and promises, and reactive programming. These techniques will help you adopt a test-driven approach to your workflow in order to use Swift Package Manager and integrate the framework into the original code base, along with Unit and UI testing. By the end of the book, you'll be able to build applications that are scalable, faster, and easier to maintain.
Table of Contents (22 chapters)
Title Page
Copyright and Credits
About Packt
Contributors
Preface
Index

Preface

Hands-on Design Patterns in Swift provides a complete overview of how to implement classic design patterns in Swift. Swift is a modern language, and for users coming from a purely object-oriented language background, it may feel overwhelming. It has peculiar characteristics that create new programming paradigms, such as protocol programming, and appropriate solutions to problems such as type erasure. Both of these are covered in this book.

Design patterns do not live in isolation, however, but they help to solve real-world problems. Particular attention is given to presenting them in a number of realistic scenarios.

The goal of Swift is to create robust and maintainable apps, be they mobile or server. However, well-known techniques such as dependency injection and automatic testing are taken from other programming languages.

Finally, since most of the modern software relies upon open source, the final chapter shows how to release and maintain a Swift open source package.

Who this book is for

This book is designed for intermediate and advanced developers who already have experience of another programming language and some experience of Swift.

Those readers with no previous experience in Swift may find an examination of the basics in the first part of the book beneficial.

The second part demonstrates how to implement the classic creational, behavioral, and structural design patterns, as well as those peculiar to Swift patterns. In this section, experienced developers will find both similarities and differences with their favorite programming language.

This isn't an academic book, but it aspires to show readers how to implement an app in a pragmatic and practical way. Consequently, the third part is devoted to how to implement an application architecture, presenting patterns such as MVC and MVVM, as well as how to create a couple of modules loosely with dependency injection, and how to handle asynchronous code with futures, promises and reactive programming.

The final part shows how to make apps robust and maintainable. After providing advanced readers with an overview of the Swift testing ecosystem, particular attention is given to the open source maintainers between the readers, showing how to release and maintain a Swift open source package or app.

What this book covers

Chapter 1, Refreshing the Basics, introduces the building blocks that facilitate the writing of Swift code: classes, structs, enums, functions, and closures. Those basics are essential to the Swift language and for successfully applying efficient design patterns and best practices.

Chapter 2, Understanding ARC and Memory Management, describes the particular memory management strategy Swift uses. From its origins in Objective-C, during the pre-ARC era, to today, we'll discover how to properly manage our memory and object life cycles. 

Chapter 3, Diving into Foundation and the Swift Standard Library, discusses the powerful framework that comes with Swift. Alongside basic data structures such as arrays and dictionaries, it also comes with a fully featured concurrency management abstraction library (GCD), a full modern networking API (URLSession), and many more features besides.

Chapter 4, Working with Objective-C in a Mixed Code Base, covers the basics of interoperability, nullability, naming conventions, and lightweight generics, as well as the common pitfalls to avoid when bringing Objective-C code to Swift.

Chapter 5, Creational Patterns, dives into the traditional creational design patterns. Examples of Singleton, Abstract Factories, Prototype, Factory, and Builder are shown by means of detailed use cases.

Chapter 6, Structural Patterns, explores the most popular structural patterns, starting with the adapter pattern. We'll follow that up with implementing decorators, facades, and proxies, and finish with exploring composite, bridge, and flyweight patterns.

Chapter 7, Behavioral Patterns, shows patterns that identify common communication strategies between different entities. We'll see examples of the state pattern, observer/observable, memento, visitor, and the strategy pattern.

Chapter 8, Swift-Oriented Patterns, presents patterns peculiar to Swift. After introducing protocol programming, it shows how to implement the classic template pattern using protocol programming. Finally, it shows the type erasure pattern, a powerful tool for mastering generics.

Chapter 9, Using the Model-View-Controller Pattern, explores some best practices and decoupling strategies to keep the view controllers as lean as they should be. The classic Model View Controller pattern is discussed, as are other popular controllers available in UIKit and AppKit. 

Chapter 10, Model-View-ViewModel in Swift, explores an extension of MVC, the Model-View-ViewModel pattern. MVVM is a very popular and flexible pattern that avoids the "bloated view controller" effect.

Chapter 11, Implementing Dependency Injection, covers the different flavors of dependency injection and examines how each can solve a particular set of problems in real-world scenarios.

Chapter 12, Futures, Promises, and Reactive Programming, discusses how to solve the most common asynchronous code problems. It explores futures and promises as an encapsulation of work being done. Finally, it provides an overview of signals and reactive programming.

Chapter 13, Modularize Your Apps with Swift Package Manager, shows how Swift Package Manager can power your workflow and keep your project in check, all while increasing the modularity and maintainability of your code base.

Chapter 14, Testing Your Code with Unit and UI Tests, shows how to write unit tests, what they are, what you should look for, and how to get started with testability. The chapter on dependency injection concludes with a presentation of the different types of test doubles to test in isolation, along with an introduction to UI testing.

Chapter 15, Going Out in the Open (Source), discusses the steps required before you can put your project in the open, documenting the source code with Jazzy, using continuous integration with Travis, and automating release with Fastlane.

To get the most out of this book

This book uses Xcode version 10 and Swift 4.2. If you use a different version of Xcode, you will likely encounter syntax difference. To upgrade the Swift syntax and update the code examples of this book to a newer version of Xcode, you can use Xcode's Edit | Convert | To Current Swift Syntax option.

Visit https://developer.apple.com/xcode/ to download Xcode.

Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. 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/Hands-On-Design-Patterns-with-Swift. 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!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/9781789135565_ColorImages.pdf.

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system."

A block of code is set as follows:

func translate(point : Point, dx : Double, dy : Double) {
    point.x += dx
    point.y += dy
}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

func translate(point : Point, dx : Double, dy : Double) {
    point.x += dx
    point.y += dy
}

Any command-line input or output is written as follows:

$ gem install jazzy
$ jazzy

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Navigate to the Diagnostics tab."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and 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.packt.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.

Reviews

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 packt.com.