O'Reilly logo

Beginning Swift Programming by Wei-Meng Lee

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required