Book Image

Swift Data Structure and Algorithms

By : Mario Eguiluz Alebicto
Book Image

Swift Data Structure and Algorithms

By: Mario Eguiluz Alebicto

Overview of this book

Apple’s Swift language has expressive features that are familiar to those working with modern functional languages, but also provides backward support for Objective-C and Apple’s legacy frameworks. These features are attracting many new developers to start creating applications for OS X and iOS using Swift. Designing an application to scale while processing large amounts of data or provide fast and efficient searching can be complex, especially running on mobile devices with limited memory and bandwidth. Learning about best practices and knowing how to select the best data structure and algorithm in Swift is crucial to the success of your application and will help ensure your application is a success. That’s what this book will teach you. Starting at the beginning, this book will cover the basic data structures and Swift types, and introduce asymptotic analysis. You’ll learn about the standard library collections and bridging between Swift and Objective-C collections. You will see how to implement advanced data structures, sort algorithms, work with trees, advanced searching methods, use graphs, and performance and algorithm efficiency. You’ll also see how to choose the perfect algorithm for your problem.
Table of Contents (15 chapters)
Swift Data Structure and Algorithms
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface

Preface

This book aims to teach experienced developers how to leverage the latest Swift language features. With Swift, Apple's new programming language for macOS, iOS, watchOS, tvOS, and Linux, you can write software that is fast and helps promote safer coding practices. With Swift and Xcode playgrounds, Apple has made it easy for developers to learn about the best practices and new programming concepts. Apple has open sourced the Swift language, that is, they have made it available on a wide range of platforms now, not just the Apple ecosystem. By doing this, developers are now able to develop server-side code on multiple platforms, in addition to developing code for the traditional line of Apple products.

Today, so many consumers are dependent on their smartphones and Internet access, the effect being the amount of data is growing exponentially, and being able to process, sort, and search that data as quickly as possible is more important than ever. Understanding how data structures and algorithms affect the efficiency of processing huge amounts of data is the key to any successful application or software library.

You will learn about the important Swift features and the most relevant data structures and algorithms, using a hands-on approach with code samples in Xcode Playgrounds for each data structure and algorithm covered in this book. We teach you factors to consider when selecting one type or method over another. You also learn how to measure the performance of your code using asymptotic analysis, a concept commonly used in the software industry in order to choose the best algorithm and data structure for a particular use case.

With knowledge learned in this book, you will have the best tools available to help you develop efficient and scalable software for your applications.

We hope you enjoy reading the book and learning more about some of the advanced Swift features, while also understanding how slight modifications to your existing code can dramatically improve the performance of your applications.

What this book covers 

Chapter 1, Walking Across the Playground, contains an introduction to data structures and algorithms, the Swift REPL, and how to enter Swift statements into it to produce results on the fly.

Chapter 2, Working with Commonly Used Data Structures, covers classes and structures, the implementation details for the array, dictionary, and set collection types, how Swift interoperates with Objective-C and the C system libraries, and protocol-oriented programming introduction.

Chapter 3, Standing on the Shoulders of Giants, covers how to conform to Swift protocols, how to implement a stack and queue structure, and implement several types so you can gain experience for choosing the right type based on the requirements of your application.

Chapter 4, Sorting Algorithms, covers algorithms, sorting algorithms and how to apply them using an array data structure, explore different algorithms that use comparison sorting and look at both simple sorting and divide-and-conquer strategies.

Chapter 5, Seeing the Forest through the Tree, explains the tree data structure, including a definition and its properties, an overview of different types of trees, such as binary trees, binary search trees (BST), B–trees, and splay trees with implementation details.

Chapter 6, Advanced Searching Methods, covers more advanced tree structures: red-black trees, AVL trees, Trie trees (Radix trees) and covers several Substring search algorithms.

Chapter 7, Graph Algorithms, explains graph theory and data structures for graphs, as well as depth-first search, breadth-first search, spanning tree, shortest path, and SwiftGraph.

Chapter 8, Performance and Algorithm Efficiency, shows you algorithm efficiency and how to measure it, Big-O notation, orders of common functions, and evaluating runtime complexity.

Chapter 9, Choosing the Perfect Algorithm, learn how to deal with problems that require algorithms and data structures by creating a high level solution, writing the implementation in Swift, calculating Big-O complexities of our solution to check if the algorithm behaves properly in a real-world situation, measuring and detecting bottlenecks, and modifying the solution to achieve better performance.

What you need for this book 

The basic requirements for this book are as follows:

  • Xcode, at least v8.1

  • macOS Sierra 10.12 or OS X El Capitan 10.11.5 or later

Who this book is for 

Swift Data Structures and Algorithms is intended for developers who want to learn how to implement and use common data structures and algorithms natively in Swift. Whether you are a self-taught developer without a formal technical background or you have a degree in Computer Science, this book will provide with the knowledge you need to develop advanced data structures and algorithms in Swift using the latest language features. An emphasis is placed on resource usage to ensure the code will run on a range of platforms from mobile to server. A previous background in an object-oriented language is helpful, but not required, as each concept starts with a basic introductory.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "The initWith portion of the name is removed from the method name."

A block of code is set as follows:

class MovieList { 
    private var tracks = ["The Godfather", "The Dark Knight", "Pulp
    Fiction"] 
     
    subscript(index: Int) -> String { 
         
        get { 
            return self.tracks[index] 
        } 
         
        set { 
            self.tracks[index] = newValue 
        } 
    } 
} 

Any command-line input or output is written as follows:

erik@iMac ~ swift
Welcome to Apple Swift version 3.0 (swiftlang-800.0.46.2 clang-
800.0.38). Type :help for assistance.
  1>

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In Xcode, go to File | New | Playground, and call it B05101_6_RedBlackTree."

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important to us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code 

You can download the example code files for this book 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 files e-mailed directly to you.

You can download the code files by following these steps:

  1. Log in or register to our website using your e-mail address and password.

  2. Hover the mouse pointer on the SUPPORT tab at the top.

  3. Click on Code Downloads & Errata.

  4. Enter the name of the book in the Search box.

  5. Select the book for which you're looking to download the code files.

  6. Choose from the drop-down menu where you purchased this book from.

  7. Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  • WinRAR / 7-Zip for Windows

  • Zipeg / iZip / UnRarX for Mac

  • 7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Swift-Data-Structure-and-Algorithms. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Downloading the color images of this book 

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/SwiftDataStructureandAlgorithms_ColorImages.pdf .

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.