12 Generics

WHAT YOU WILL LEARN IN THIS CHAPTER:                  

  • The motivation behind generics
  • How to implement generic functions
  • How to implement generic functions using multiple parameters
  • How to specify type constraints in generics
  • How to define generic classes
  • How to define generic structures
  • How to define generic extensions
  • How to use generics in protocols
  • Specifying requirements for generics in associated types

Most modern programming languages support a language feature known as generics, and Swift is no exception. Generics enable you to write highly reusable functions that can work with a variety of data types. With generics, you specify a placeholder for the data type that your generic code (functions, classes, structures, protocols, etc.) is working with. The actual data type to use is specified only at a later stage when the generic code is being used. In this chapter, you will learn about Swift’s support for generics.

UNDERSTANDING GENERICS

Generics are one of the most important features of Swift. Generics are so important that most of the types and classes in Swift are created using them. The best way to understand generics is to look at an example.

Consider the following function:

	func swapNums(inout item1:Int, inout item2:Int) {
		let temp = item1
		item1 = item2
		item2 = temp
	}

The swapNums() function declares two inout parameters and exchanges their values. The following code snippet shows how to use the swapNums() function to swap the values of two

Get Beginning Swift Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.