
Mastering Swift 6
Description
Alles über E-Books | Antworten auf Fragen rund um E-Books, Kopierschutz und Dateiformate finden Sie in unserem Info- & Hilfebereich.
- Learn advanced techniques like concurrency, memory management, Generics, and Swift Testing
- Apply best practices in Swift to write clean, scalable, and maintainable code
- Purchase of the print or Kindle book includes a free PDF eBook
Book DescriptionThis seventh edition of Mastering Swift 6 is your ultimate guide to harnessing the full power of Swift. Whether you're aiming to optimize the performance of your applications or looking to explore the exciting new features in Swift 6.2, this book has you covered. The author distills his 28 years of experience in the Engineering and IT fields to help you dive deep into advanced concepts and techniques, such as concurrency, memory management, and Generics, all essential for creating high-performance applications. The chapters take you on a flexible journey, covering Swift 6.2's newest features alongside advanced programming topics such as reflection, concurrency, and Generics. Packed with best practices, testing strategies, and modern programming techniques, this book equips you with the skills to develop scalable, high-performance applications with confidence. Whether you're looking to stay competitive or simply want to excel in Swift 6, this book provides the tools and knowledge you need to succeed.What you will learn - Optimize your application's performance to meet the demands of the modern user
- Develop readable, well-structured code by utilizing Swift development strategies
- Use reflection with the Mirror API to observe your application's execution at runtime
- Conquer advanced topics, such as concurrency, memory management, and generics
- Find out how to use result builders and how to create custom operators in Swift
- Effectively test your Swift code with the all-new Swift Testing framework
Who this book is forThis book is for developers who have a fundamental grasp of the Swift language and aspire to take their development skills to the next level by learning about the advanced topics and techniques of the Swift language. All examples are compatible with Linux, in addition to the MacOS, iOS, iPadOS, VisionOS, and WatchOS platforms, unless otherwise noted.
All prices
More details
Content
- Cover
- Title Page
- Copyright Page
- Contributors
- Table of Contents
- Preface
- Chapter 1: The Evolution of Swift
- Getting the most out of this book - get to know your free benefits
- How Swift has evolved
- Swift was born
- Swift evolved
- What's new with Swift 6?
- Migrating existing projects to Swift 6
- How swift.org can help you
- Comprehensive documentation and guides
- The Swift standard library and Core Libraries
- The Swift Package Manager
- Continuous integration and source compatibility
- Contributing to Swift
- A thriving community
- Summary
- Chapter 2: Closures and Result Builders
- Introducing closures
- Simple closures
- Shorthand syntax for closures
- Using closures with Swift arrays
- Multiple trailing closures
- Advanced closures example
- Result builders
- Summary
- Chapter 3: Protocols and Protocol Extensions
- Protocols as types
- Polymorphism with protocols
- Typecasting with protocols
- Using protocols with enumerations
- Protocol extensions
- Any and any
- Uppercase "Any"
- Existential "any" in Swift
- Adopting protocols using a synthesized implementation
- Summary
- Chapter 4: Generics
- Introducing generics
- Generic functions
- Defining generic functions
- Calling generic functions
- Type constraints
- Generic types
- Conditionally adding extensions with generics
- Conditionally adding functions
- Conditional conformance
- Generic subscripts
- Associated types
- Implicitly opened existentials
- Summary
- Chapter 5: Value and Reference Types
- Value types and reference types
- inout parameters and value types
- Noncopyable types
- Recursive data types for reference types
- Inheritance for reference types
- Dynamic dispatch
- Copy-on-write
- Creating a backend storage type
- Creating a Queue type
- Using the Queue type
- Summary
- Chapter 6: Enumerations
- Raw values
- Associated values
- Pattern matching
- Enumeration iteration
- Going beyond basic values
- Summary
- Chapter 7: Reflection
- Reflection and the Mirror API
- Getting started with the Mirror API
- CustomReflectable protocol
- Serializing objects
- Summary
- Chapter 8: Error Handling and Availability
- Native error handling
- Representing errors
- Throwing errors
- Catching errors
- Using the do-catch block
- Using multiple catch statements
- Using error propagation
- Using a forced-try expression
- Using an optional try
- The LocalizedError protocol
- Defer functions
- Multi-pattern catch clauses
- Typed throws
- The availability attribute
- Unavailability
- Summary
- Chapter 9: Regular Expressions
- How regular expressions are built
- Literals
- Metacharacters
- Quantifiers
- Anchors
- Modifiers
- Character classes
- Grouping and capturing
- Assertions
- Regular expression literals
- Regex type
- RegexBuilder
- Converting regular expressions to RegexBuilder format
- Transform a match with RegexBuilder
- Capture a match with RegexBuilder
- Summary
- Chapter 10: Custom Subscripting
- Introducing subscripts
- Subscripts with Swift arrays
- Creating and using custom subscripts
- Read-only custom subscripts
- Calculated subscripts
- Subscript values
- Static subscripts
- External names for subscripts
- Multidimensional subscripts
- Extending types with subscripts
- When not to use a custom subscript
- Summary
- Chapter 11: Property Observers and Wrappers
- Introducing property observers
- Using property observers
- Introducing property wrappers
- Using property wrappers
- Projected values
- Observation of values
- Summary
- Chapter 12: Dynamic Member Lookup and Key Paths
- Dynamic member lookup
- Key paths
- Understanding key paths
- Static properties
- Key paths in functions
- The map and filter functions with key paths
- Using key paths and dynamic member lookups together
- Summary
- Chapter 13: Grand Central Dispatch
- Concurrency and parallelism
- GCD
- Creating functions for our queues
- Creating queues
- Creating and using a concurrent queue
- Creating and using a serial queue
- Executing code on the main queue function
- async versus sync methods with GCD
- Using asyncAfter
- Dispatch groups
- DispatchWorkItem
- DispatchTime
- DispatchWallTime
- Barriers
- Dispatch semaphores
- Summary
- Chapter 14: Structured Concurrency
- Data race conditions and Swift 6
- Asynchronous functions
- async and await
- Calling multiple asynchronous functions
- Tasks
- Detaching tasks
- Canceling tasks
- Starting a task synchronously
- Task naming
- Task groups
- Actors
- Global actors
- Sendable types
- Adapting completion handlers to async/await
- Strict concurrency checking
- Default actor isolation
- Summary
- Chapter 15: Memory Management
- Introducing ARC
- How ARC works
- Strong reference cycles
- Unowned references
- Weak references
- Retain cycles and closures
- InlineArray
- Summary
- Chapter 16: Advanced and Custom Operators
- Bits and bytes
- Endianness
- Bitwise operators
- Printing binary numbers
- The bitwise AND operator
- The bitwise OR operator
- The bitwise XOR operator
- The bitwise NOT operator
- Bitwise shift operators
- BinaryInteger extension
- Overflow operators
- Operator methods
- Custom operators
- Summary
- Chapter 17: Access Controls
- Introducing access control
- Access control levels
- Open access
- Public access
- Internal access
- File-private access
- Private access
- Access levels with enumerations
- Access levels for getters and setters
- Best practices for access control
- Use the most restrictive access level by default
- Encapsulate implementation details
- Use extensions wisely
- Maintain consistency
- Summary
- Chapter 18: Swift Testing
- Getting started with Swift Testing
- Adding Swift Testing to an existing Xcode project
- Adding Swift Testing to an existing Swift Package Manager project
- Building blocks for Swift Testing
- Declaring the @Test function
- Expectations
- #require macro
- Confirmations
- Exit tests
- Traits
- Suites
- Swift Testing example
- Creating our calculator
- Using the @testable attribute
- Testing our calculator
- Summary
- Chapter 19: Object-Oriented Programming
- What is OOP?
- Requirements for the example code
- Using object-oriented design
- Visualizing our class hierarchy
- Forming our object-oriented design
- Using our vehicle types
- Issues with the object-oriented design
- Summary
- Chapter 20: Protocol-Oriented Programming
- What is POP?
- Requirements for the sample code
- Using POP
- Visualizing our protocol-oriented design
- Forming our protocol-oriented design
- Using our vehicle types
- Protocol inheritance
- Protocol composition
- Protocol-oriented design
- Swift standard library
- Summary
- Chapter 21: Functional Programming with Swift
- Core principles of functional programming
- Immutability
- Pure functions
- First-class functions
- Higher-order functions
- Advanced functional programming techniques
- Function composition
- Currying
- Recursion
- Summary
- Chapter 22: Unlock Your Book'sExclusive Benefits
- How to unlock these benefits in three easy steps
- Packt Page
- Other Books You May Enjoy
- Index
Preface
Since its surprise debut at WWDC in June 2014, Swift has rapidly redefined how we build software, combining safety, speed, and a clear, concise syntax to power everything from iOS, macOS, watchOS, and tvOS apps to server-side services on Linux and, since September 2020, native Windows development. Born from Chris Lattner's vision of a modern successor to Objective-C, Swift's modern features, such as optionals, generics, and closures, combined with its powerful type inference system, have made code more expressive, reliable, and enjoyable to write. While Apple's decision to open-source the language in 2015 and stabilize its ABI in Swift 5 has created a vibrant community around swift.org. In this book, we'll explore some of Swift's most advanced features to help you take your development to the next level, writing cleaner, more powerful, and highly optimized applications.
Who this book is for
This book is written for developers with an understanding of the Swift programming language who are looking to elevate their skills by exploring advanced topics and techniques. The examples provided are compatible with application development across all Apple platforms, including macOS, iOS, iPadOS, visionOS, and watchOS, as well as Linux and Windows development, unless otherwise specified.
What this book covers
Chapter 1, The Evolution of Swift, highlights the evolution of the Swift language, showing how its history shaped the features and design choices that developers use today. It also introduces swift.org, a key resource providing documentation, collaboration opportunities, and support for the Swift community.
Chapter 2, Closures and Result Builders, introduces closures, which are self-contained blocks of code that can capture and retain references to variables from their surrounding context. Additionally, we will look at result builders, a feature that allows developers to create custom Domain-Specific Languages (DSLs) used for defining complex data structures.
Chapter 3, Protocols and Protocol Extensions, explores protocols, highlighting how they can be used as full-fledged types that enable polymorphism through the unified interface they provide. It also introduces protocol extensions, which help reduce code duplication by offering default implementations for methods and properties. Additionally, the chapter covers the use of Any to represent an instance of any type, and existential any, which allows storing any value that conforms to a specific protocol.
Chapter 4, Generics, explores generic types, which serve as the foundation for many types in the Swift standard library. Real-world examples demonstrate how to create and use generics effectively. Additionally, the chapter covers topics such as generic subscripts and associated types, illustrating how generics can enhance the flexibility of our code.
Chapter 5, Value and Reference Types, explains the differences between value types and reference types in Swift. This chapter includes practical examples of structures and classes, covering features such as copy-on-write for optimizing performance with large value types and recursive data types for reference types. Additionally, we will look at dynamic dispatch, which, while introducing some performance overhead, enables the flexibility needed for class hierarchies.
Chapter 6, Enumerations, looks at Swift enumerations and what makes them more powerful than enumerations in other languages. We will also look at how to use raw values and how pattern matching can simplify our code. Additionally, we will see how associated values allow Swift enumerations to represent complex data structures.
Chapter 7, Reflection, looks at what reflection is and how the Mirror API in Swift enables it. We will demonstrate how to use the Mirror API to inspect structures and classes, revealing details such as property names, values, and type information.
Chapter 8, Error Handling and Availability, looks at Swift's error handling mechanisms and how errors are defined using types conforming to the Error protocol. We will demonstrate how to throw errors in functions using the throws keyword and handle them with do-catch blocks. Additionally, we will discuss Swift's availability and unavailability attributes for conditional code execution based on platform versions.
Chapter 9, Regular Expressions, explores the power of regular expressions for pattern matching and text manipulation, from simple searches to complex data extraction. The chapter shows how Swift supports regular expressions with regular expression literals and the Regex type. Additionally, Regex Builder is introduced, which offers a clearer, more intuitive way to define patterns, and we will look into advanced features such as transforming and capturing matches using references.
Chapter 10, Custom Subscripting, explores how incorporating subscripts into custom types can improve readability and usability. We will examine how to create multi-parameter subscripts and discuss how to use subscripts appropriately, consistent with the Swift language itself.
Chapter 11, Property Observers and Wrappers, explores how property observers and wrappers automatically respond to changes in property values, which improves the responsiveness of our applications. We will examine how property observers trigger actions while property wrappers abstract property management into reuseable types.
Chapter 12, Dynamic Member Lookup and Key Paths, explores how dynamic member lookups allow properties to be resolved at runtime. Additionally, we will examine how key paths offer a type-safe way to access and manipulate properties using the \. syntax.
Chapter 13, Grand Central Dispatch, explores the difference between concurrency and parallelism. We will see how Grand Central Dispatch uses both serial and concurrent queues to handle task execution. Additionally, we will highlight how it has tools for managing UI updates and scheduling tasks effectively.
Chapter 14, Structured Concurrency, explores how async and await offer intuitive ways to handle asynchronous tasks, allowing functions to pause and resume without blocking the main thread. We will examine how tasks and task groups further control and coordinate asynchronous operations. Additionally, we will look at actors and the role they play in managing state safety.
Chapter 15, Memory Management, examines how Swift uses Automatic Reference Counting (ARC) to manage memory for reference types such as classes. We will discuss how to use weak and unowned references to avoid strong reference cycles, which can hinder ARC from deallocating reference types, causing memory leaks.
Chapter 16, Advanced and Custom Operators, explores advanced bitwise operators, such as the AND, OR, XOR, and NOT operators, for manipulating variable bits and the right and left shift operators for shifting bits. We will also look at how to add operator methods to our custom types.
Chapter 17, Access Controls, looks at how access controls are used to ensure code security by restricting access to specific parts of the code base. We will examine the five access levels that Swift provides and how to apply them effectively. Additionally, we will see how applying the principle of least privilege will ensure that only the necessary parts of our code are accessible.
Chapter 18, Swift Testing, looks at Swift Testing, which is a powerful new testing framework introduced in Swift 6. We will explore the key building blocks, such as the @Test attribute and the #expect and #require macros, as well as the use of traits for adding metadata.
Chapter 19, Object-Oriented Programming with Swift, looks at object-oriented programming and how its design principles can be effectively applied with Swift to create structured and reusable code.
Chapter 20, Protocol-Oriented Programming with Swift, explores the core principles of protocol-oriented programming with Swift and how it differs from traditional object-oriented programming. Additionally, we will examine how Swift's standard library is built with a protocol-oriented approach.
Chapter 21, Functional Programming with Swift, looks at Swift's support for functional programming concepts such as immutability, pure functions, and first-class functions. We will also explore advanced techniques such as function composition, currying, and recursion to manage complex operations effectively.
To get the most out of this book
To get the most out of this book, you will need a basic understanding of the Swift language and a basic understanding of modern development techniques. All code examples have been tested using Xcode 26 on a Mac; however, all examples should also work using Swift on Linux or Windows.
Download the example code files
The code bundle for the book is hosted on GitHub at...
System requirements
File format: ePUB
Copy protection: Adobe-DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Install the free reader Adobe Digital Editions prior to download (see eBook Help).
- Tablet/smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook before downloading (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePub works well for novels and non-fiction books – i.e., „flowing” text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook uses Adobe-DRM, a „hard” copy protection. If the necessary requirements are not met, unfortunately you will not be able to open the eBook. You will therefore need to prepare your reading hardware before downloading.
Please note: We strongly recommend that you authorise using your personal Adobe ID after installation of any reading software.
For more information, see our ebook Help page.
File format: ePUB
Copy protection: without DRM (Digital Rights Management)
System requirements:
- Computer (Windows; MacOS X; Linux): Use a reader that can handle the file format ePUB, such as Adobe Digital Editions or FBReader – both free (see eBook Help).
- Tablet/Smartphone (Android; iOS): Install the free app Adobe Digital Editions or the app PocketBook (see eBook Help).
- E-reader: Bookeen, Kobo, Pocketbook, Sony, Tolino and many more (not Kindle).
The file format ePUB works well for novels and non-fiction books – i.e., 'flowing' text without complex layout. On an e-reader or smartphone, line and page breaks automatically adjust to fit the small displays.
This eBook does not use copy protection or Digital Rights Management
For more information, see our eBook Help page.