Book Image

Mastering Swift 5.3 - Sixth Edition

By : Jon Hoffman
Book Image

Mastering Swift 5.3 - Sixth Edition

By: Jon Hoffman

Overview of this book

Over the years, Mastering Swift has proven itself among developers as a popular choice for an in-depth and practical guide to the Swift programming language. This sixth edition comes with the latest features, an overall revision to align with Swift 5.3, and two new chapters on building swift from source and advanced operators. From the basics of the language to popular features such as concurrency, generics, and memory management, this in-depth guide will help you develop your expertise and mastery of the language. As you progress, you will gain practical insights into some of the most sophisticated elements in Swift development, including protocol extensions, error handling, and closures. The book will also show you how to use and apply them in your own projects. In later chapters, you will understand how to use the power of protocol-oriented programming to write flexible and easier-to-manage code in Swift. Finally, you will learn how to add the copy-on-write feature to your custom value types, along with understanding how to avoid memory management issues caused by strong reference cycles. By the end of this Swift book, you will have mastered the Swift 5.3 language and developed the skills you need to effectively use its features to build robust applications.
Table of Contents (23 chapters)
21
Other Books You May Enjoy
22
Index

Overflow operators

Swift, at its core, is designed for safety. One of these safety mechanisms is the inability to insert a number into a variable when the variable type is too small to hold it. As an example, the following code will throw the following error: arithmetic operation '255 + 1' (on type 'UInt8') results in an overflow:

let b: UInt8 = UInt8.max +1

The reason an error is thrown is we are trying to add one to the maximum number that a UInt8 can hold. This error checking can help prevent unexpected and hard-to-trace issues in our applications. Let's take a second and look at what would happen if Swift did not throw an error when an overflow occurs. In a UInt8 variable, which is an 8-bit unsigned integer, the number 255 is stored like this, where all of the bits are set to 1:

Figure 15.8: The binary representation of 255

Now if we add 1 to this number, the new number will be stored like this:

Figure 15.9: Overflow when...