O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Mastering Swift 4 - Fourth Edition

Book Description

Dive into the latest release of the Swift programming language with this advanced development book for building highly performant applications.

About This Book

  • Harness the latest and most advanced features of Swift 4 to develop quality iOS and macOS applications
  • Comprehensive coverage of all the advanced features of Swift and guidance on advanced design techniques
  • Dive deep into protocol extensions, learn new error handling model, and use featured Swift design patterns to write more efficient code
  • Get to grips with advanced design techniques to write smarter, cleaner Swift code

Who This Book Is For

This book is for developers who want to delve into the newest version of Swift. If you are a developer who learns best by looking at and working with code, then this book is for you. A basic understanding of Apple's tools is beneficial but not mandatory.

What You Will Learn

  • Delve into the core components of Swift 4.0, including operators, collections, control flows, and functions
  • Create and use classes, structures, and enumerations
  • Understand protocol-oriented design and see how it can help you write better code
  • Develop a practical understanding of subscripts and extensions
  • Add concurrency to your applications using Grand Central Dispatch and Operation Queues
  • Implement generics and closures to write very flexible and reusable code
  • Make use of Swift’s error handling and availability features to write safer code

In Detail

Swift is the definitive language for Apple development today. It's a vital part of any iOS and macOS developer's skillset, helping them to build the most impressive and popular apps on the App Store—the sort of apps that are essential to iPhone and iPad users every day. With version 4.0, the Swift team has added new features to improve the development experience, making it easier to get the results you want and customers expect.

Inside, you'll find the key features of Swift 4.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability and ARC to closures and concurrency, this advanced Swift guide will develop your expertise and help you become fluent in this vital programming language.

We'll give you an in-depth knowledge of some of the most sophisticated elements of Swift development, including protocol extensions, error-handling, design patterns, and concurrency. We'll guide you on how to use and apply them in your own projects. You'll see how to leverage the power of protocol-oriented programming to write flexible and easier-to-manage code.

Style and Approach

A Step-by-step advanced guide

Downloading the example code for this book. You can download the example code files for all Packt books you have purchased 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 code file.

Table of Contents

  1. Preface
    1. What this book covers
    2. What you need for this book
    3. Who this book is for
    4. Conventions
    5. Reader feedback
    6. Customer support
      1. Downloading the example code
      2. Downloading the color images of this book
      3. Errata
      4. Piracy
      5. Questions
  2. Taking the First Steps with Swift
    1. What is Swift?
      1. Swift features
    2. Playgrounds
      1. Getting started with Playgrounds
      2. iOS, tvOS, and macOS Playgrounds
      3. Showing images in a Playground
      4. Creating and displaying graphs in Playgrounds
      5. What Playgrounds are not
      6. Swift language syntax
      7. Comments
      8. Semicolons
      9. Parentheses
      10. Curly brackets
      11. An assignment operator does not return a value
      12. Spaces are optional in conditional and assignment statements
    3. Hello World
    4. Summary
  3. Learning about Variables, Constants, Strings, and Operators
    1. Constants and variables
      1. Defining constants and variables
      2. Type safety
      3. Type inference
      4. Explicit types
      5. Numeric types
        1. Integer types
        2. Floating-point and Double values
      6. The Boolean type
      7. The string type
      8. Optional variables
      9. Optional binding
      10. Optional chaining
      11. Enumerations
    2. Operators
      1. The assignment operator
      2. Comparison operators
      3. Arithmetic operators
      4. The remainder operator
      5. Compound assignment operators
      6. The ternary conditional operator
      7. The logical NOT operator
      8. The logical AND operator
      9. The logical OR operator
    3. Summary
  4. Using Swift Collections and the Tuple Type
    1. Swift collection types
    2. Mutability
    3. Arrays
      1. Creating and initializing arrays
      2. Accessing the array elements
      3. Counting the elements of an array
      4. Is the array empty?
      5. Appending to an array
      6. Inserting a value into an array
      7. Replacing elements in an array
      8. Removing elements from an array
      9. Merging two arrays
      10. Retrieving a subarray from an array
      11. Making bulk changes to an array
      12. Algorithms for arrays
        1. Sort
        2. Sorted
        3. Filter
        4. Map
        5. forEach
      13. Iterating over an array
    4. Dictionaries
      1. Creating and initializing dictionaries
      2. Accessing dictionary values
      3. Counting the key or values in a dictionary
      4. Is the dictionary empty?
      5. Updating the value of a key
      6. Adding a key-value pair
      7. Removing a key-value pair
    5. Set
      1. Initializing a set
      2. Inserting items into a set
      3. Determining the number of items in a set
      4. Checking whether a set contains an item
      5. Iterating over a set
      6. Removing items in a set
      7. Set operations
    6. Tuples
    7. Summary
  5. Control Flow and Functions
    1. What have we learned so far?
      1. Curly brackets
      2. Parentheses
    2. Control flow
      1. Conditional statements
        1. The if statement
        2. Conditional code execution with the if...else statement
        3. The guard statement
      2. The for-in loop
        1. Using the for...in loop
      3. The while loop
        1. Using the while loop
        2. Using the repeat-while loop
      4. The switch statement
      5. Using case and where statements with conditional statements
        1. Filtering with the where statement
        2. Filtering with the for-case statement
        3. Using the if-case statement
      6. Control transfer statements
        1. The continue statement
        2. The break statement
        3. The fallthrough statement
    3. Functions
      1. Using a single parameter function
      2. Using a multi-parameter function
      3. Defining a parameter's default values
      4. Returning multiple values from a function
      5. Returning optional values
      6. Adding external parameter names
      7. Using variadic parameters
      8. Inout parameters
    4. Putting it all together
    5. Summary
  6. Classes and Structures
    1. What are classes and structures?
      1. Similarities between classes and structures
      2. Differences between classes and structures
      3. Value versus reference types
    2. Creating a class or structure
      1. Properties
      2. Stored properties
      3. Computed properties
      4. Property observers
      5. Methods
    3. Custom initializers
      1. Internal and external parameter names
      2. Failable initializers
    4. Access controls
    5. Inheritance
    6. Overriding methods and properties
      1. Overriding methods
      2. Overriding properties
      3. Preventing overrides
    7. Protocols
    8. Protocol syntax
      1. Property requirements
      2. Method requirements
    9. Extensions
    10. Memory management
      1. How ARC works
      2. Strong reference cycles
    11. Summary
  7. Using Protocols and Protocol Extensions
    1. Protocols as types
    2. Polymorphism with protocols
    3. Type casting with protocols
    4. Protocol extensions
    5. Do I need to use protocols?
    6. Swift's standard library
    7. Summary
  8. Protocol-Oriented Design
    1. Requirements
    2. Object-oriented design
      1. Protocol-oriented design
      2. Protocol inheritance
      3. Protocol composition
      4. Protocol-oriented design
      5. Using the where statement with protocols
    3. Structures versus classes
    4. The array structure
    5. Summary
  9. Writing Safer Code with Availability and Error Handling
    1. Native error handling
      1. Representing errors
      2. Throwing errors
      3. Catching errors
    2. The availability attribute
    3. Summary
  10. Custom Subscripting
    1. Introducing subscripts
    2. Subscripts with Swift arrays
    3. Creating and using custom subscripts
    4. Read-only custom subscripts
    5. Calculated subscripts
    6. Subscript values
    7. External names for subscripts
    8. Multidimensional subscripts
    9. When not to use a custom subscript
    10. Summary
  11. Using Optional Types
    1. Introducing optionals
    2. The need for optional types in Swift
      1. Defining an optional
      2. Using optionals
        1. Forced unwrapping of an optional
        2. Optional binding
        3. Returning optionals from functions and methods
        4. Using an optional as a parameter in a function or method
        5. Optional binding with the guard statement
        6. Optional types with tuples
    3. Optional chaining
      1. The nil coalescing operator
    4. Summary
  12. Working with Generics
    1. An introduction to generics
    2. Generic functions
    3. Generic types
    4. Generic subscripts
    5. Associated types
    6. Summary
  13. Working with Closures
    1. An introduction to closures
    2. Simple closures
    3. Shorthand syntax for closures
    4. Using closures with Swift's array algorithms
    5. Standalone closures and good style guidelines
    6. Changing functionality
    7. Selecting a closure based on results
    8. Creating strong reference cycles with closures
    9. Summary
  14. Using Mix and Match
    1. What is mix and match?
    2. When to use mix and match
    3. Using Swift and Objective-C together in the same project
      1. Creating the project
      2. Adding Swift files to the Objective-C project
      3. The Objective-C bridging header file - part 1
      4. Adding the Objective-C file to the project
      5. The Messages Objective-C class
      6. The Objective-C bridging header file - part 2
      7. The MessageBuilder Swift class - accessing Objective-C code from Swift
      8. The Objective-C class - accessing Swift code from Objective-C
    4. Summary
  15. Concurrency and Parallelism in Swift
    1. Concurrency and parallelism
      1. Grand Central Dispatch
      2. Calculation type
        1. Creating queues
          1. Creating and using a concurrent queue
          2. Creating and using a serial queue
        2. async versus sync
        3. Executing code on the main queue function
        4. Using asyncAfter
      3. Using the Operation and OperationQueue types
        1. Using BlockOperation
        2. Using the addOperation() method of the operation queue
        3. Subclassing the Operation class
    2. Summary
  16. Swift Formatting and Style Guide
    1. What is a programming style guide?
    2. Your style guide
      1. Do not use semicolons at the end of statements
      2. Do not use parentheses for conditional statements
      3. Naming
        1. Custom types
        2. Functions and methods
        3. Constants and variables
        4. Indenting
      4. Comments
      5. Using the self keyword
      6. Constants and variables
      7. Optional types
        1. Using optional binding
        2. Using optional chaining instead of optional binding for multiple unwrapping
      8. Using type inference
      9. Using shorthand declaration for collections
      10. Using switch rather than multiple if statements
      11. Don't leave commented-out code in your application
    3. Summary
  17. Swift Core Libraries
    1. Apple's URL loading system
      1. URLSession
      2. URLSessionConfiguration
      3. URLSessionTask
      4. URL
      5. URLRequest
      6. HTTPURLResponse
      7. REST web services
      8. Making an HTTP GET Request
      9. Making an HTTP POST request
    2. Formatter
      1. DateFormatter
      2. NumberFormatter
      3. FileManager
    3. Encoding and Decoding JSON Data
      1. Using JSONEncoder
      2. Using JSONDecoder
    4. Summary
  18. Adopting Design Patterns in Swift
    1. What are design patterns?
    2. Creational patterns
      1. The singleton design pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the singleton pattern
      2. The builder design pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the builder pattern
    3. Structural design patterns
      1. The bridge pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the bridge pattern
      2. The façade pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the façade pattern
      3. The proxy design pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the proxy pattern
    4. Behavioral design patterns
      1. The command design pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the command pattern
      2. The strategy pattern
        1. Understanding the problem
        2. Understanding the solution
        3. Implementing the strategy pattern
    5. Summary