You are previewing Mastering Swift.
O'Reilly logo
Mastering Swift

Book Description

Master Apple's new Swift programming language by following the best practices to write efficient and powerful code

In Detail

Swift is Apple's new innovative and user-friendly development language, which is packed with modern features to make programming easier, fun, and flexible.

This book begins by giving you a solid Introduction to the Swift programming language so you can quickly begin developing applications using this interesting language. It also covers advanced topics such as Objective-C interoperability, ARC, closures, and concurrency. Each concept covered is backed up with example code and demonstrates how to properly execute it. Next, you will be taught about all of the advanced features of Swift, and its interaction with Apple's APIs and libraries. You'll then learn to interact with REST-based web services using Swift. We will conclude the book by getting equipped to design and build applications using established design patterns.

What You Will Learn

  • Prototype and test code in a Playground

  • Understand the basics of Swift, including operators, collections, control flows, and functions

  • Create and use Classes, Structures, and Enums, including object-oriented topics such as inheritance, protocols, and Extensions

  • Dwell into Subscripts, Optionals, and closures with real-world scenarios

  • Employ Grand Central Dispatch to add concurrency to your applications

  • Study the Objective-C interoperability with mix and match

  • Access network resources using Swift

  • Implement various standard design patterns in the Swift language

  • 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 If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.

    Table of Contents

    1. Mastering Swift
      1. Table of Contents
      2. Mastering Swift
      3. Credits
      4. About the Author
      5. About the Reviewers
        1. Support files, eBooks, discount offers, and more
          1. Why subscribe?
          2. Free access for Packt account holders
      7. 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
      8. 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. Displaying graphs in Playgrounds
          5. What Playgrounds are not
        3. Swift language syntax
          2. Semicolons
          3. Parentheses
          4. Curly braces
          5. Assignment operator (=) does not return a value
          6. Spaces are optional in conditional and assignment statements
        4. Hello world
        5. Summary
      9. 2. Learning about Variables, Constants, Strings, and Operators
        1. Constants and variables
        2. Defining constants and variables
          1. Type safety
          2. Type inference
          3. Explicit types
        3. Numeric types
          1. Integers
          2. Floating-point
        4. The Boolean type
        5. The string type
        6. Optional variables
        7. Enumerations
        8. Operators
          1. The assignment operator
          2. Comparison operators
          3. Arithmetic operators
          4. The remainder operator
          5. Increment and decrement operators
          6. Compound assignment operators
          7. The ternary conditional operator
          8. The logical NOT operator
          9. The logical AND operator
          10. The logical OR operator
        9. Summary
      10. 3. Using Collections and Cocoa Data Types
        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. Adding 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
          14. Iterating over an array
        4. Dictionaries
          1. Creating and initializing dictionaries
          2. Accessing dictionary values
          3. Counting key/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. Tuples
        6. Using Cocoa data types
          1. NSNumber
          2. NSString data type
          3. NSArray
          4. NSDictionary
        7. Foundation data types
        8. Summary
      11. 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. Executing codes with the if-else statement
          2. The for loops
            1. Using the for loop variant
            2. Using the for-in loop variant
          3. The while loop
            1. Using the while loop
            2. Using the do-while loop
          4. The switch statement
          5. 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 multiparameter 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 shorthand for external parameter names
          8. Using variadic parameters
          9. Parameters as variables
          10. Using inout parameters
          11. Nesting functions
        4. Summary
      12. 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. Initializer
          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
          1. Protocol syntax
          2. Property requirements
          3. Method requirements
          4. Optional requirements
        7. Extensions
        8. Memory management
          1. Reference versus value types
          2. The working of ARC
          3. Strong reference cycles
        9. Summary
      13. 6. Working with XML and JSON Data
        1. XML and JSON
        2. Common files
        3. XML and the NSXMLParser class
        4. Using the NSXMLParserDelegate protocol
        5. Parsing XML documents
          1. XML and NSXMLDocument
        6. XML and manually building XML documents
        7. JSON and NSJSONSerialization
          1. Parsing a JSON document
          2. Creating a JSON document
        8. Summary
      14. 7. 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. Subscripts with ranges
        8. External names for subscripts
        9. Multidimensional subscripts
        10. When not to use a custom subscript
        11. Summary
      15. 8. Using Optional Type and Optional Chaining
        1. Introducing optionals
        2. The need for optional types in Swift
          1. Defining an optional
          2. Using optionals
            1. Unwrapping an optional
            2. Optional binding
            3. Returning optionals from functions, methods, and subscripts
            4. Using optionals as a parameter in a function or method
            5. Optional types with tuples
        3. Optional chaining
          1. The nil coalescing operator
        4. Summary
      16. 9. Working with Generics
        1. Introduction to generics
        2. Generic functions
        3. Generic types
        4. Associated types
        5. Summary
      17. 10. Working with Closures
        1. Introducing 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. Select a closure based on results
        8. Strong reference cycles with closures
        9. Summary
      18. 11. Using Mix and Match
        1. What is mix and match?
        2. Using Swift and Objective-C together in the same project
          1. Creating the project
          2. Adding the Swift file 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
        3. Summary
      19. 12. Concurrency and Parallelism in Swift
        1. Concurrency and parallelism
          1. Grand Central Dispatch
          2. Creating and managing dispatch queues
            1. Creating queues with the dispatch_queue_create() function
              1. Creating concurrent dispatch queues with the dispatch_queue_create() function and using the dispatch_asynch() function
              2. Creating a serial dispatch queue with the dispatch_queue_create() function and using the dispatch_sync() function
            2. Requesting concurrent queues with the dispatch_get_global_queue() function
            3. Requesting the main queue with the dispatch_get_main_queue() function
            4. Using the dispatch_after() function
            5. Using the dispatch_once() function
          3. Using NSOperation and NSOperationQueue types
            1. Using the NSBlockOperation implementation of NSOperation
            2. Using the addOperationWithBlock() method of the operation queue
            3. Subclassing the NSOperation class
        2. Summary
      20. 13. 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. Classes
            2. Functions and methods
            3. Constants and variables
            4. Indenting
          5. Using the self keyword
          6. Types
          7. Constants and variables
          8. Optional types
            1. Use optional binding
            2. Use optional chaining over optional binding for multiple unwrapping
          9. Use type inference
          10. Use shorthand declaration for collections
          11. Use for-in loops over for loops
          12. Use switch rather than multiple if statements
          13. Don't leave commented out code in your application
          14. Grand central dispatch
          15. Set the attribute in the dispatch_queue_create() function
          16. Use reverse DNS name for the tag parameter of the dispatch_queue_create() function
            1. Use dispatch_get_global_queue() over dispatch_queue_create()
        3. Summary
      21. 14. Network Development with Swift
        1. What is network development?
        2. An overview of the URL session classes
          1. NSURLSession
          2. NSURLSessionConfiguration
          3. NSURLSessionTask
          4. Using the NSURL class
          5. NSMutableURLRequest
          6. NSURLHTTPResponse
        3. REST web services
        4. Making an HTTP GET request
        5. Making an HTTP POST request
        6. Encoding a URL
        7. Checking network connection
        8. RSNetworking
          1. RSURLRequest
          2. RSTransaction and RSTransactionRequest
            1. RSTransaction
            2. RSTransactionRequest
            3. Extensions
        9. Summary
      22. 15. Adopting Design Patterns in Swift
        1. What are design patterns?
        2. Creational patterns
          1. The singleton design pattern
          2. The builder design pattern
          3. The factory method pattern
        3. Structural design patterns
          1. The bridge pattern
          2. The facade pattern
          3. The proxy design pattern
        4. Behavioral design patterns
          1. The command design pattern
          2. The strategy pattern
        5. Summary
      23. Index