Swift: Developing iOS Applications

Book description

Unleash the power of Swift and discover the skills required to build incredible robust iOS applications

About This Book

  • Write expressive, understandable, and maintainable Swift 2 code with this hands-on course
  • Unveil the complex underpinnings of Swift to turn your app ideas into reality
  • Specialize in developing real iOS apps, and 2D and 3D video games using Swift and Cocoapods
  • 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 course would be for app developers who are new to developing for iOS or OSX and are trying to get grips with Swift for the first time.

What You Will Learn

  • From a solid understanding of the Swift 2 language
  • Get to know the practical aspects of how a computer program actually works
  • Understand the paradigms used by Apple's frameworks, so you are not intimidated by them
  • Create a server in Swift to deliver JSON data to an iOS app
  • Take advantage of Cocoapods to use third-party libraries
  • Build games with SpriteKit and SceneKit
  • Develop an app running on the cloud to act as an API server for your client's apps
  • 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
  • Master Objective-C interoperability with mix and match
  • Access network resources using Swift
  • Implement various standard design patterns in the Swift language

In Detail

The Swift??Developing iOS Applications course will take you on a journey to become an efficient iOS and OS X developer, with the latest trending topic in town. Right from the basics to the advanced level topics, this course would cover everything in detail. We'll embark our journey by dividing the learning path into four modules. Each of these modules are a mini course in their own right; and as you complete each one, you'll gain key skills and be ready for the material in the next module.

The first module is like a step-by-step guide to programming in Swift 2. Each topic is separated into compressible sections that are full of practical examples and easy-to-understand explanations. Each section builds on the previous topics, so you can develop a proficient and comprehensive understanding of app development in Swift 2. By the end of this module, you'll have a basic understanding of Swift 2 and its functionalities.

The second module will be the an easy-to-follow guide filled with tutorials to show you how to build real-world apps. The difficulty and complexity level increases chapter by chapter. Each chapter is dedicated to build a new app, beginning from a basic and unstyled app through to a full 3D game. The last two chapters show you how to build a complete client-server e-commerce app right from scratch. You'll be able to build well-designed apps, effectively use AutoLayout, develop videogames, and build server apps.

The third and the last module of our course will take 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.

Style and approach

This course includes all the resources that will help you jump into the app development .This course covers all the important aspects Swift application development and is divided into individual modules so that you develop your skill after the completion of a module and get ready for the next. Through this comprehensive course, you'll learn how to use Swift programming with hands-on examples from scratch to finish!

Table of contents

  1. Swift: Developing iOS Applications
    1. Table of Contents
    2. Swift: Developing iOS Applications
    3. Swift: Developing iOS Applications
    4. Credits
    5. Preface
      1. What this learning path covers
      2. What you need for this learning path
      3. Who this learning path is for
      4. Reader feedback
      5. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    6. 1. Module 1
      1. 1. Introducing Swift
        1. Defining our goals for this book
        2. Setting up the development environment
        3. Running our first swift code
        4. Understanding playgrounds
        5. Learning with this book
        6. Summary
      2. 2. Building Blocks – Variables, Collections, and Flow Control
        1. Core Swift types
          1. Constants and variables
          2. Containers
            1. Tuples
            2. Arrays
            3. Dictionaries
        2. Swift's type system
        3. Printing to the console
        4. Control flow
          1. Conditionals
          2. Switches
          3. Loops
        5. Functions
          1. Basic functions
          2. Parameterized functions
          3. Functions that return values
          4. Functions with default arguments
          5. Guard statement
        6. Bringing it all together
        7. Summary
      3. 3. One Piece at a Time – Types, Scopes, and Projects
        1. Structs
          1. Types versus instances
          2. Properties
          3. Member and static methods
          4. Computed properties
          5. Reacting to property changes
          6. Subscripts
          7. Custom initialization
        2. Classes
          1. Inheriting from another class
          2. Initialization
            1. Overriding initializer
            2. Required initializer
            3. Designated and convenience initializers
          3. Overriding methods and computed properties
            1. Methods
            2. Computed properties
          4. Casting
            1. Upcasting
            2. Downcasting
        3. Enumerations
          1. Basic declaration
          2. Testing enumeration values
          3. Raw values
          4. Associated values
          5. Methods and properties
        4. Projects
          1. Setting up a command-line Xcode project
          2. Creating and using an external file
          3. Interfacing with code from other files
          4. File organization and navigation
        5. Extensions
        6. Scope
          1. How scope is defined
          2. Nested types
        7. Access control
        8. Summary
      4. 4. To Be or Not To Be – Optionals
        1. Defining an optional
        2. Unwrapping an optional
          1. Optional binding
          2. Forced unwrapping
          3. Nil coalescing
        3. Optional chaining
        4. Implicitly unwrapped optionals
        5. Debugging optionals
        6. The underlying implementation
        7. Summary
      5. 5. A Modern Paradigm – Closures and Functional Programming
        1. Functional programming philosophy
          1. State and side effects
          2. Declarative versus imperative code
        2. Closures
          1. Closures as variables
          2. Closures as parameters
          3. Syntactic sugar
        3. Building blocks of functional programming in Swift
          1. Filter
          2. Reduce
          3. Map
          4. Sort
          5. How these affect the state and nature of code
        4. Lazy evaluation
        5. Example
        6. Summary
      6. 6. Make Swift Work For You – Protocols and Generics
        1. Protocols
          1. Defining a protocol
          2. Implementing a protocol
          3. Using type aliases
        2. Generics
          1. Generic function
          2. Generic type
          3. Type constraints
            1. Protocol constraints
            2. Where clauses for protocols
            3. Where clauses for equality
        3. Extending generics
          1. Adding methods to all forms of a generic
          2. Adding methods to only certain instances of a generic
          3. Extending protocols
        4. Putting protocols and generics to use
          1. Generators
          2. Sequences
          3. Product of Fibonacci numbers under 50
        5. Summary
      7. 7. Everything Is Connected – Memory Management
        1. Computer data storage
          1. File system
          2. Memory
        2. Value types versus reference types
          1. Determining value type or reference type
          2. Behavior on assignment
          3. Behavior on input
          4. Closure capture behavior
        3. Automatic reference counting
          1. Object relationships
            1. Strong
            2. Weak
            3. Unowned
        4. Strong reference cycles
          1. Between objects
            1. Spotting
            2. Fixing
          2. With closures
            1. Spotting
            2. Fixing
        5. Lost objects
          1. Between objects
          2. With closures
        6. Structures versus classes
        7. Summary
      8. 8. Paths Less Traveled – Error Handling
        1. Throwing errors
          1. Defining an error type
          2. Defining a function that throws an error
          3. Implementing a function that throws an error
        2. Handling errors
          1. Forceful try
          2. Optional try
          3. Catching an error
          4. Propagating errors
        3. Cleaning up in error situations
          1. Order of execution when errors occur
          2. Deferring execution
        4. Summary
      9. 9. Writing Code the Swift Way – Design Patterns and Techniques
        1. What is a design pattern?
        2. Behavioral patterns
          1. Iterator
          2. Observer
            1. Callback
            2. Notification center
        3. Structural patterns
          1. Composite
            1. Hierarchies
            2. Alternative to subclassing
          2. Delegate
          3. Model view controller
        4. Creational patterns
          1. Singleton/shared instance
          2. Abstract factory
        5. Using associated values effectively
          1. Replacing class hierarchies
          2. Concisely representing state
        6. Extending system types to reduce code
        7. Lazy properties
          1. Avoiding unnecessary memory usage
          2. Avoiding unnecessary processing
          3. Localizing logic to the concerned property
        8. Summary
      10. 10. Harnessing the Past – Understanding and Translating Objective-C
        1. Swift's relationship to Objective-C
        2. Background of Objective-C
        3. Constants and variables
          1. Value types
          2. Reference types
        4. Containers
          1. Arrays
          2. Dictionaries
        5. Control flow
          1. Conditionals
          2. Switches
          3. Loops
        6. Functions
        7. Types
          1. Structures
          2. Enumerations
          3. Classes
            1. Basic class
            2. Initializers
            3. Properties
            4. Methods
            5. Inheritance
          4. Categories
          5. Protocols
          6. Blocks
        8. Projects
          1. Header files
          2. Implementation files
          3. Organization
        9. Calling Objective-C code from Swift
          1. Bridging header
        10. Using functions
          1. Using types
          2. Containers
          3. Annotations
            1. Nullability
            2. Container element types
        11. Summary
      11. 11. A Whole New World – Developing an App
        1. Conceptualizing the app
          1. Features
          2. Interface
          3. Data
        2. Setting up the app project
        3. Configuring the user interface
        4. Running the app
        5. Allowing picture taking
        6. Temporarily saving a photo
        7. Populating our photo grid
        8. Refactoring to respect model-view-controller
        9. Permanently saving a photo
        10. Summary
      12. 12. What's Next? – Resources, Advice, and the Next Steps
        1. Apple's documentation
        2. Forums and blogs
          1. Blog posts
          2. Forums
        3. Prominent figures
        4. Podcasts
        5. Summary
    7. 2. Module 2
      1. 1. Welcome to the World of Swift
        1. The first look at Swift
          1. Let's go to the playground
          2. The building blocks – variables and constants
          3. Collecting variables in containers
          4. Controlling the flow
          5. Transforming the values using functions
          6. Structs – custom compound types
          7. Classes – common behavior objects
          8. Loose coupling with protocols
          9. Composing objects using protocol extensions
          10. Checking the existence of an optional value
          11. Enumerations on steroids
          12. Extended pattern matching
          13. Catching errors
          14. Swift functional programming patterns
        2. Summary
      2. 2. Building a Guess the Number App
        1. The app is…
          1. Building a skeleton app
          2. Adding the graphics components
          3. Connecting the dots
          4. Adding the code
        2. Summary
      3. 3. A Memory Game in Swift
        1. The app is…
        2. Building the skeleton of the app
        3. The menu screen
          1. Implementing the basic menu screen
          2. Creating a nice menu screen
        4. The game screen
          1. The structure
          2. Adding a collection view
          3. Sizing the components
        5. Connecting the dataSource and the delegate
        6. Implementing a deck of cards
          1. What we are expecting
          2. The card entity
          3. Crafting the deck
          4. Shuffling the deck
          5. Finishing the deck
          6. Put the cards on the table
          7. Adding the assets
          8. The CardCell structure
          9. Handling touches
        7. Finishing the game
          1. Implementing the game logic
          2. We got a pair
          3. We made the wrong move
          4. Et voilà! The game is completed
        8. Summary
      4. 4. A TodoList App in Swift
        1. The app is…
        2. Building a skeleton app
          1. Implementing an empty app
          2. Adding third-party libraries with CocoaPods
          3. Implementing the Todos view controller
        3. Building the Todos screen
          1. Adding entities
          2. Implementing datastore
          3. Connecting datastore and View Controller
          4. Configuring tableView
          5. Finishing touches
          6. Swipe that cell!
        4. Adding a Todo task
          1. The add a Todo view
          2. The add a Todo View Controller
          3. Finishing TodoDatastore
          4. List View Controller
          5. Where do we go from here?
        5. Summary
      5. 5. A Pretty Weather App
        1. The app is…
        2. Building the skeleton
          1. Creating the project
          2. Adding assets
        3. Implementing the UI
          1. The UI in blocks
        4. Completing the UI
          1. Implementing CurrentWeatherView
          2. Building WeatherHourlyForecastView
          3. Seeing the next day's forecast in WeatherDaysForecastView
        5. Blurring the background
        6. Downloading the background image
          1. Searching in Flickr
        7. Geolocalising the app
          1. Using Core Location
        8. Retrieving the actual forecast
          1. Getting the forecast from OpenWeatherMap
          2. Rendering CurrentWeatherView
          3. Rendering WeatherHourlyForecastView
          4. Rendering WeatherDaysForecastView
        9. Connecting to the server
        10. Where do we go from here?
        11. Summary
      6. 6. Flappy Swift
        1. The app is…
        2. Building the skeleton of the app
          1. Creating the project
          2. Implementing the menu
        3. A stage for a bird
          1. SpriteKit in a nutshell
          2. Explaining the code
          3. Simulating a three-dimensional world using parallax
          4. How to implement scrolling
        4. A flying bird
          1. Adding the Bird node
          2. Making the bird flap
        5. Pipes!
          1. Implementing the pipes node
        6. Making the components interact
          1. Setting up the collision-detection engine
        7. Completing the game
          1. Colliding with pipes
          2. Adding the score
          3. Adding a restart pop-up
        8. Summary
      7. 7. Polishing Flappy Swift
        1. Adding juiciness
          1. Let there be sounds!
          2. Playing the soundtrack
          3. Shaking the screen!
        2. Integrating with Game Center
          1. What Game Center provides
          2. Setting up Game Center
          3. Creating an app record on iTunes Connect
          4. Enabling Game Center
          5. Creating fake user accounts to test Game Center
          6. Authenticating a player
        3. Summary
      8. 8. Cube Runner
        1. The app is…
        2. Introduction to SceneKit
          1. What is SceneKit?
          2. Building an empty scene
          3. Adding a green torus
          4. Let there be light!
          5. Let's make it move!
        3. Implementing Cube Runner
          1. The game skeleton
          2. Implementing the menu
        4. Flying in a 3D world
          1. Setting up a scene
          2. Adding a fighter
          3. Texturing the world
          4. Make it move
          5. Adding cubes
          6. Adding more obstacles
        5. Adding a few touches
          1. The score
          2. Let's add music
        6. Summary
      9. 9. Completing Cube Runner
        1. Creating a real game
          1. Detecting collisions
          2. Game over!
          3. Adding the juice
          4. Game Center
        2. Summary
      10. 10. ASAP – an E-commerce App in Swift
        1. The app is…
          1. The first requirement: login and registration
          2. The second requirement: the products grid
          3. The third requirement: the open cart
        2. The skeleton app and register screen
          1. The skeleton app
        3. The ASAP e-commerce store
          1. The e-commerce product list
          2. The product cell
          3. Parsing and storing products
        4. The ASAP cart
          1. Adding a product to the cart
          2. Removing items from cart and checkout
        5. Summary
      11. 11. ASAPServer, a Server in Swift
        1. The interface of the ASAP Server
        2. One skeleton server for two OSes
          1. An OS X skeleton server
            1. Preparing the OS X environment
            2. The HelloWorld skeleton server
            3. Preparing the Linux environment
        3. The ASAPServer
          1. The Products
          2. The cart
          3. The order
        4. Connecting the ASAP app
          1. The products
          2. The Cart
          3. The order
        5. Summary
    8. 3. Module 3
      1. 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
      2. 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
      3. 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
      4. 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
      5. 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
      6. 6. Using Protocols and Protocol Extensions
        1. Protocols as types
        2. Polymorphism with protocols
        3. Type casting with protocols
        4. Protocol extensions
        5. Summary
      7. 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
      8. 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
      9. 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
      10. 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
      11. 11. Working with Generics
        1. An introduction to generics
        2. Generic functions
        3. Generic types
        4. Associated types
        5. Summary
      12. 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
      13. 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
      14. 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
      15. 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
      16. 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
      17. 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
    9. A. Biblography
    10. Index

Product information

  • Title: Swift: Developing iOS Applications
  • Author(s): Andrew J Wagner, Giordano Scalzo, Jon Hoffman
  • Release date: August 2016
  • Publisher(s): Packt Publishing
  • ISBN: 9781787120242