Chapter    16

Generics

Generics are one of the most powerful aspects of the Swift language. If you are coming from Objective-C, this is a new concept, and it might take some getting used to. The main purpose of generics is to enable the writing of adaptable, reusable code.

Generic Functions

Let’s take a look at a simple function that compares two integers. The function takes two arguments of type Int and returns a Boolean true if two values are the same.

func equalInts(a : Int, b : Int) -> Bool {    return a == b}

What if you want to compare two double values or strings? You have to write two new functions:

func equalDoubles(a : Double, b : Double) -> Bool {    return a == b}func equalStings(a : String, b : String) -> Bool {    return a == b ...

Get Learn Swift on the Mac: For OS X and iOS now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.