Generics - Introduction
Introduction
Overview of This Module
In this module, you’ll learn more about generics, protocols, and functional programming. These tools enable you to use object-oriented principles and maintain type safety while keeping your code from growing too large.
Lesson 1: The Swift standard library is built on generic types. You use them every time you create an array or decode JSON. You can write generic functions and types that can work with any type, setting constraints where necessary.
Lesson 2: Swift is swift largely because so many standard types are structs, not classes, and Swift encourages you to create structs wherever possible. Structs don’t have inheritance to support polymorphism — they use protocols, instead. And protocols work just as well with classes, enums and other protocols — you can compose or inherit protocols, giving you unlimited flexibility in creating a modular app architecture.
Lesson 3: Swift isn’t a functional programming language, but it has features that support functional programming principles. Swift is swifter when you use immutable values, and immutability is a core principle of functional programming. The map, filter, and reduce functions that you use with Swift collections are examples of the higher-order functions that are fundamental to functional programming.
Introduction to Generics
Swift is a type-safe language. You can’t even add an Int to a Double unless you convert one type to the other. The compiler keeps an eye on every line of code and flags any type mismatches. If you want to write a function or data structure that performs the same operations on different types of objects, it might seem that you must write the same code multiple times, once for each object type. But this would violate the DRY (Don’t Repeat Yourself) principle of software development. Fortunately, there’s a solution: Generic functions and types let you write code once and use it for different object types while maintaining type-safety.
Upon completing this lesson, you’ll be able to:
- Explain how generics are used in Swift.
- Describe how constraints can be applied to generics to narrow their scope.