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

Book Description

Dive into the latest release of the Swift programming language with this advanced Apple development book for creating exceptional iOS and osX applications

About This Book

  • Harness the latest and most advanced features of Swift 2 to develop quality iOS and OSX 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

  • Who This Book Is For

    This book is for developers that want to dive into the newest version of Swift. If you want in-depth knowledge of some of the most sophisticated elements of Swift development including protocol extensions, error-handling, design patterns, and concurrency, Mastering Swift 2 gives you guidance on how to use and apply them in your own projects.

    What You Will Learn

  • Dive into the core components of Swift 2 including operators, collections, control flow, and functions

  • Create and use classes, structures, and enums including object-oriented topics such as inheritance, protocols, and extensions

  • Develop a practical understanding of subscripts, optionals, and closures

  • Learn how to use the new protocol extension and error handling features of Swift 2

  • Add concurrency to your applications using Grand Central Dispatch

  • Master Objective-C interoperability with Mix and Match

  • Access network resources using Swift

  • Implement various standard design patterns in the Swift language

  • In Detail

    At their Worldwide Developer’s conference (WWDC) in 2015, Apple announced Swift 2, a major update to the innovative programming language they first unveiled to the world the year before. Swift 2 features exciting enhancements to the original iteration of Swift, acting, as Apple put it themselves as “a successor to the C and Objective-C languages.” – This book demonstrates how to get the most from these new features, and gives you the skills and knowledge you need to develop dynamic iOS and OS X applications.

    Learn how to harness the newest features of Swift 2 todevelop advanced applications on a wide range of platforms with this cutting-edge development guide. Exploring and demonstrating how to tackle advanced topics such as Objective-C interoperability, ARC, closures, and concurrency, you’ll develop your Swift expertise and become even more fluent in this vital and innovative language. With examples that demonstrate how to put the concepts into practice, and design patterns and best practices, you’ll be writing better iOS and OSX applications in with a new level of sophistication and control.

    Style and approach

    This book takes an example-based approach where each concept covered is supported by example code to not only give you a good understanding of the concept, but also to demonstrate how to properly implement it.

    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 2
      1. Table of Contents
      2. Mastering Swift 2
      3. Credits
      4. About the Author
      5. About the Reviewer
      6. www.PacktPub.com
        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. Creating and displaying graphs in Playgrounds
          5. What Playgrounds are not
          6. Swift language syntax
          7. Comments
          8. Semicolons
          9. Parentheses
          10. Curly braces
          11. An assignment operator does not return a value
          12. Spaces are optional in conditional and assignment statements
        3. Hello World
        4. Summary
      9. 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. 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
        3. 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. sortInPlace
            2. sort
            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. Using Cocoa data types
          1. NSNumber
          2. NSString
          3. NSArray
          4. NSDictionary
        8. Foundation data types
        9. 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. Conditional code execution 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 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 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 variadic parameters
          8. Parameters as variables
          9. Using inout parameters
          10. Nesting functions
        4. Putting it all together
        5. 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. 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
          3. Optional requirements
        8. Extensions
        9. Memory management
          1. Reference versus value types
          2. The working of ARC
          3. Strong reference cycles
        10. Summary
      13. 6. Using Protocols and Protocol Extensions
        1. Protocols as types
        2. Polymorphism with protocols
        3. Type casting with protocols
        4. Protocol extensions
        5. Summary
      14. 7. Writing Safer Code with Availability and Error Handling
        1. Error handling prior to Swift 2.0
        2. Error handling in Swift 2
          1. Representing errors
          2. Throwing errors
          3. Catching errors
        3. The availability attribute
        4. Summary
      15. 8. 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
      16. 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. Subscripts with ranges
        8. External names for subscripts
        9. Multidimensional subscripts
        10. When not to use a custom subscript
        11. Summary
      17. 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 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
      18. 11. Working with Generics
        1. An introduction to generics
        2. Generic functions
        3. Generic types
        4. Associated types
        5. Summary
      19. 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
      20. 13. 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 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
      21. 14. 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
              2. Creating a serial dispatch queue with the dispatch_queue_create() 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
      22. 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. Classes
            2. Functions and methods
            3. Constants and variables
            4. Indenting
          4. Comments
          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 a reverse DNS name for the tag parameter of the dispatch_queue_create() function
          17. Use dispatch_get_global_queue() over dispatch_queue_create()
        3. Summary
      23. 16. 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. Checking network connection
        7. RSNetworking2 for Swift 2
          1. RSURLRequest
          2. RSTransaction and RSTransactionRequest
            1. RSTransaction
            2. RSTransactionRequest
            3. Extensions
        8. Summary
      24. 17. Adopting Design Patterns in Swift
        1. Value versus reference types
        2. What are design patterns
        3. Creational patterns
          1. The singleton design pattern
          2. The builder design pattern
          3. The factory method pattern
        4. Structural design patterns
          1. The bridge pattern
          2. The façade pattern
          3. The proxy design pattern
        5. Behavioral design patterns
          1. The command design pattern
          2. The strategy pattern
        6. Summary
      25. Index