Book Image

Learning Swift Second Edition - Second Edition

By : Andrew J Wagner
Book Image

Learning Swift Second Edition - Second Edition

By: Andrew J Wagner

Overview of this book

Swift is Apple’s new programming language and the future of iOS and OS X app development. It is a high-performance language that feels like a modern scripting language. On the surface, Swift is easy to jump into, but it has complex underpinnings that are critical to becoming proficient at turning an idea into reality. This book is an approachable, step-by-step introduction into programming with Swift for everyone. It begins by giving you an overview of the key features through practical examples and progresses to more advanced topics that help differentiate the proficient developers from the mediocre ones. It covers important concepts such as Variables, Optionals, Closures, Generics, and Memory Management. Mixed in with those concepts, it also helps you learn the art of programming such as maintainability, useful design patterns, and resources to further your knowledge. This all culminates in writing a basic iOS app that will get you well on your way to turning your own app ideas into reality.
Table of Contents (19 chapters)
Learning Swift Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Putting protocols and generics to use


One cool part of Swift is generators and sequences. They provide an easy way to iterate over a list of values. Ultimately, they boil down to two different protocols: GeneratorType and SequenceType. If you implement the SequenceType protocol in your custom types, it allows you to use the for-in loop over an instance of your type. In this section, we will look at how we can do that.

Generators

The most critical part of this is the GeneratorType protocol. Essentially, a generator is an object that you can repeatedly ask for the next object in a series until there are no objects left. Most of the time you can simply use an array for this, but it is not always the best solution. For example, you can even make a generator that is infinite.

There is a famous infinite series of numbers called the Fibonacci sequence, where every number in the series is the sum of the two previous numbers. This is especially famous because it is found all over nature from the number...