Book Image

Mastering Swift

By : Jon Hoffman
Book Image

Mastering Swift

By: Jon Hoffman

Overview of this book

Table of Contents (22 chapters)
Mastering Swift
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Introduction to generics


The concept of generics has been around for a while so it should not be a new concept to developers coming from languages such as Java or C#. Swift's implementation of generics is very similar to these languages. For those developers coming from other languages, such as Objective-C, which do not have generics, such as Java and C#, they might seem a bit foreign at first.

Generics allow us to write very flexible and reusable code that avoids duplication. With a type safe language, such as Swift, we often need to write functions or types that are valid for multiple types. For example, we might need to write a function that swaps the values of two variables; however, we may use this function to swap two strings types, two int types, and two double types. Without generics, we will need to write three separate functions; however, with generics, we can write one generic function to provide the swap functionality for multiple types. Generics allow us to tell a function or...