O'Reilly logo

Learn Swift 2 on the Mac, Second Edition by Waqar Malik

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

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 ...

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