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 3

Book Description

Dive into the latest release of the Swift programming language with this advanced Apple development book

About This Book

  • Discover the new features and improvements to Swift 3
  • Get to grips with advanced design patterns and techniques to write smarter, cleaner Swift code
  • Become a more fluent Swift developer and build powerful, impressive iOS and OS X applications.

Who This Book Is For

This book is for developers who want to dive into the newest version of Swift.

If you are a developer that 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

  • Dive into the core components of Swift 3.0, including operators, collections, control flow, and functions
  • Create and use classes, structures, and enums
  • Understand object-oriented Swift and see how to tackle inheritance, protocols, and extensions
  • Develop a practical understanding of subscripts, optionals, and closures
  • See how to use the new protocol extension and error handling features of Swift 3.0
  • Add concurrency to your applications using Grand Central Dispatch

In Detail

Swift is the definitive language of Apple development today. It’s a vital part of any iOS and OS X 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 3.0, the Swift team have 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 3.0 and quickly learn how to use the newest updates to your development advantage. From Objective-C interoperability to ARC, to closures and concurrency, this advanced Swift guide will develop your expertise and make you more fluent in this vital programming language.

We give you in-depth knowledge of some of the most sophisticated elements of Swift development including protocol extensions, error-handling, design patterns, and concurrency, and guide you on how to use and apply them in your own projects. You'll see how even the most challenging design patterns and programming techniques can be used to write cleaner code and to build more performant iOS and OS X applications.

By the end of this book, you’ll have a handle on effective design patterns and techniques, which means you’ll soon be writing better iOS and OS X applications with a new level of sophistication and control.

Style and approach

Packed with practical examples that show you how to put the concepts you learn into practice quickly, we’ll takes you through some of the most advanced and sophisticated elements of the language in a practical and actionable way. You can also download the code to use yourself

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. Mastering Swift 3
    1. Mastering Swift 3
    2. Credits
    3. About the Author
    4. About the Reviewer
    5. www.PacktPub.com
      1. Why subscribe?
    6. 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
    7. 1. Taking the First Steps with Swift
      1. What is Swift?
        1. Swift features
      2. Playgrounds
        1. Getting started with Playgrounds
        2. iOS and OS X 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 for control statements
        11. An assignment operator does not return a value
        12. Spaces are optional in conditional and assignment statements
      3. Hello World
      4. Summary
    8. 2. 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. Integers
          2. Floating-point
        6. The Boolean type
        7. The string type
        8. Optional variables
        9. 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
    9. 3. 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. Reversing an array
        11. Retrieving a subarray from an array
        12. Making bulk changes to an array
        13. Algorithms for arrays
          1. Sort
          2. Sorted
          3. Filter
          4. Map
          5. forEach
        14. Iterating over an array
      4. Dictionaries
        1. Creating and initializing dictionaries
        2. Accessing dictionary values
        3. Counting 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. 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
    10. 4. Control Flow and Functions
      1. What we have 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
        2. The for 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
          4. The guard 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
        9. Nesting functions
      4. Putting it all together
      5. Summary
    11. 5. 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. Inheritance
      5. Overriding methods and properties
        1. Overriding methods
        2. Overriding properties
        3. Preventing overrides
      6. Protocols
      7. Protocol syntax
        1. Property requirements
        2. Method requirements
      8. Extensions
      9. Memory management
        1. How ARC works
        2. Strong reference cycles
      10. Summary
    12. 6. Using Protocols and Protocol Extensions
      1. Protocols as types
      2. Polymorphism with protocols
      3. Type casting with protocols
      4. Protocol extensions
      5. Summary
    13. 7. Protocol-Oriented Design
      1. Requirements
      2. Object-Oriented design
        1. Protocol-Oriented design
        2. Protocol inheritance
        3. Protocol composition
        4. Animal-protocol oriented design
        5. Using the where statement with protocols
      3. Summary
    14. 8. Writing Safer Code with Availability and Error Handling
      1. Error handling prior to Swift 2.0
      2. Native error handling
        1. Representing errors
        2. Throwing errors
        3. Catching errors
      3. The availability attribute
      4. Summary
    15. 9. Custom Subscripting
      1. Introducing subscripts
      2. Subscripts with Swift arrays
      3. Read and write 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
    16. 10. 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, methods, and subscripts
          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
    17. 11. Working with Generics
      1. An introduction to generics
      2. Generic functions
      3. Generic types
      4. Associated types
      5. When not to use generics
      6. Summary
    18. 12. 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
    19. 13. 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
    20. 14. 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 Operation and OperationQueue types
          1. Using BlockOperation
          2. Using the addOperation() method of the operation queue
          3. Subclassing the Operation class
      2. Summary
    21. 15. 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. Use optional binding
          2. Use optional chaining instead of optional binding for multiple unwrapping
        8. Use type inference
        9. Use shorthand declaration for collections
        10. Use switch rather than multiple if statements
        11. Don't leave commented-out code in your application
      3. Summary
    22. 16. Swifts 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
        4. JSONSerialization
          1. Parsing a JSON document
        5. Creating a JSON document
      3. Summary
    23. 17. 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