Andrés Ibañez Kautsch

Modern Concurrency on Apple Platforms

Using async/await with Swift

Andrés Ibañez Kautsch
La Paz, Bolivia
ISBN 978-1-4842-8694-4e-ISBN 978-1-4842-8695-1
© Andrés Ibañez Kautsch 2023
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress Media, LLC, part of Springer Nature.

The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.

To my mother Renata and to my brother Gastón, for all the support and patience they have always shown and for everything they have always done for me.

Preface

Concurrency is a topic a lot of developers find scary. And for good reason. Concurrency is probably one of the most complicated topics in the world of programming. When you look at it from a very high level, concurrency allows us to do a lot of work at the same time. Sometimes related, sometimes unrelated. The definition is simple, but as a programmer, it is hard to reason about concurrent programs. We learn to write code that can be read from top to bottom, and code usually makes sense when you read it in such a manner. In fact, the way developers reason about code is not too different to how non-programmers reason about a cooking recipe. Humans can understand anything they read if it is structured and makes sense.

But the very nature of concurrency breaks this top-to-bottom reading flow. Not only do we need to reason about concurrency differently, but we also need to keep in mind other factors that make it harder, such as shared mutable data, locks, threads…. Concurrency is naturally very complicated, especially when dealing with lower-level tools.

Luckily, the new async/await system, introduced in 2021, makes concurrency easier to reason about because it abstracts a lot of the complexity behind language-integrated features that are easy to use and hard to misuse. If you have written concurrent code before with anything other than async/await in any other platform (and that includes but is not limited to iOS, macOS, and other Apple platforms), you do not have to concern yourself with mutexes, semaphores, or any other low-level concurrency primitives. If you have never written concurrent code before, you can write amazing multithreaded software in a way that makes sense without ever having to concern yourself with the complexities of traditional concurrency. This new system is very powerful and easy to use for both developers familiar with concurrency as well as those who have never written concurrent code before.

Who This Book Is For

This book is aimed at intermediate iOS developers and above. You should find this book to be of your skill level if you have been writing Apple apps a bit over a year. Having experience with other concurrency tools in either Apple platforms or anything else may help you grasp this book easier, but previous concurrency knowledge is by no means necessary. You should be familiar with the basic process of writing and maintaining an iOS app to take advantage of this book.

How This Book Is Organized

I tried my best to organize this book in a way that makes sense. There were topics that recursively required the knowledge of other topics before they could be properly understood. For those situations, I spent a little bit more time explaining some concepts at a higher level so you could get by before they got properly introduced.

Chapter 1 introduces concurrency and its traditional problems when trying to implement it. It discusses low-level concurrency primitives and how they can be used. It also discusses the traditional problems you will find when you try to implement a concurrency system without using higher-level tools such as async/await.

Chapter 2 formally introduces “async” and “await” as keywords of the Swift language. These two keywords are essential to understand to use the concurrency system effectively. Every single topic makes use of async/await, so this chapter is completely dedicated to these keywords.

Chapter 3 introduces Continuations, a tool that helps you migrate closure-based or even delegate-based code to use async/await. This can help you “bridge” such code into the async/await world, making them easier to write and understand. You will also learn how to backport concurrent code to iOS 14 and 13.

Chapter 4 introduces the concept of Structured Concurrency. You will write your first concurrent code here. Structured concurrency helps you write multithreaded code that is easy to read and write.

Chapter 5 introduces the concept of Unstructured Concurrency, a topic that will help you write streamlined concurrent code with a little bit more of flexibility than Structured Concurrency.

Chapter 6 introduces the concept of Actors. Actors are reference types that isolate their own state, so they are useful when you need to write concurrent code that deals with shared mutable state. It helps you answer questions such as “What happens if two processes write to this variable at the same time?”

Chapter 7 is all about Sendable types, which are objects that can be used safely in concurrent code, either because they have built-in protection (such as actors) or because the developers took special care of these types to make them usable concurrently (like classes that implement their own synchronization mechanism).

Chapter 8 discusses Global Actors, a tool to help you write concurrent code that is spread out across different files and even frameworks. It also discusses the Main Actor, a global actor that you use when you need to update your app’s UI.

Chapter 9 is all about async sequences. These sequences can help you receive values over time in an asynchronous context, helping you eliminate the usage of closures and delegates in some scenarios.

Chapter 10 , the final chapter, covers the usage of a property wrapper called @TaskLocal, which you can use to share data down a concurrent tasks tree.

Before You Get Started

While Apple managed to backport the new concurrency system to iOS 13 and iOS 14, it is recommended you study this system with iOS 15. There are no native APIs that use async/await in lower iOS versions, and you would need to provide an alternative to them every time you are interested in using them.

It is recommended you have at least Xcode 13, but you should have the latest version if possible. At the time of this writing, the latest Xcode version is 13.4.1. The exercises and sample code were tested on this Xcode version. This implies your Mac will need to run macOS Monterey as Xcode 13 cannot run on anything lower than Monterey.

Acknowledgments

Whenever you decide to buy a technical book, you usually see one or two author names, and maybe a reviewer attached to it, but there are a lot of people involved in a single book, both directly and indirectly. It will not be possible to acknowledge everyone who has helped make this book possible, but I’d like to single out a few.

First, I’d like to give a big kudos to Alexis Marechal. Alexis has, in short, saved my career as a software developer. Alexis is not only a great teacher, but also a great friend. His teaching style has greatly inspired mine, and I hope I can do justice to that in this book. A big thank-you to Carlos Anibarro and Jose Luis Vera for their teachings and words of encouragement as well.

Writing a book is something I have always wanted to do, but Ernesto Campohermoso is the first person who ever asked me, “When are you going to write a book?” That single question was a great push for this book to come into existence.

Ivan Galarza is the first person I mentored in iOS development, and he became a very reliable iOS engineer in a short time thanks to all the talent he has. He was the ideal candidate to review a book in progress. His input helped me make sure everything makes sense and that this book will be something people would like to read.

A big thank-you to all the folks at Apress for the process that made writing this book possible. The entire experience has been a joy, from being contacted to write a book to turning in the final chapters. The final form of this book would have not been possible without their tenacity and amazing work ethic.

Finally, I’d like to give a big thanks to all the readers of my blog, andyibanez.com. The comments and feedback I received in the original tutorial series for this topic helped me greatly improve this book. I cannot reply to every message I get, but I am thankful to all my readers. Thank you all.

Table of Contents
Index 197
About the Author
Andrés Ibañez Kautsch

A photo of Andrés Ibañez.

started writing iOS apps as a young college student in 2011. His first introduction to concurrency programming and its common pitfalls was in an operating systems class that introduced the importance (and complexity) of writing concurrent code. Since then, he has studied how this problem is solved in Apple’s platforms, including iOS. Andy has worked in institutions that make use of concurrent technologies to keep their services running for their customers, including banks, applying the concepts to their mobile applications.
 
About the Technical Reviewer
Massimo Nardone

A photo of Massimo Nardone.

has more than 22 years of experience in security, web/mobile development, and cloud and IT architecture. His true IT passions are security and Android.

He has been programming and teaching how to program with Android, Perl, PHP, Java, VB, Python, C/C++, and MySQL for more than 20 years.

He holds a Master of Science degree in Computing Science from the University of Salerno, Italy.

He has worked as a project manager, software engineer, research engineer, chief security architect, information security manager, PCI/SCADA auditor, and senior lead IT security/cloud/SCADA architect for many years.

 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.107.181