Chapter    18

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 2 on the Mac, Second Edition 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.