Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
iOS Programming Cookbook

You're reading from   iOS Programming Cookbook Over 50 exciting and powerful recipes to help you unearth the promise of iOS programming

Arrow left icon
Product type Paperback
Published in Mar 2017
Publisher Packt
ISBN-13 9781786460981
Length 520 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Toc

Table of Contents (16) Chapters Close

Preface 1. Swift Programming Language FREE CHAPTER 2. The Essentials 3. Integrating with Messages App 4. Working with Interface Builder 5. Working with UITableView 6. Animations and Graphics 7. Multimedia 8. Concurrency 9. Location Services 10. Security and Encryption 11. Networking 12. Persisting Data with Core Data 13. Notifications 14. App Search 15. Optimizing Performance

Using generics to write generic and reusable code

Generic code is used to write reusable and flexible functionalities that can deal with any type of variables. This helps in writing reusable and clean code regardless of the type of objects your generic code deals with. An example of using generics is when you use Array and Dictionary. You can create an array of Int or String or any type you want. That's because Array is natively created and can deal with any type. Swift gives you the ability to write generic code very easily as you will see in this section.

Getting ready

Before learning how to write generic code, let's see an example of a problem that generics solve. I bet you are familiar with stack data structures and have been using it in one of the computer science courses before. Anyway, it's a kind of collection data structure that follows LIFO (Last in first out). It has very commonly used APIs for these operations, which are pop and push. Push inserts new item to the stack; pop returns the last inserted one. It's just a simple overview, as we will not explain data structures in this book as it's out of topic.

How to do it...

Here, we will create the stack data structure with/without generics:

  1. Create a new playground named Generics.
  2. Let's create the data structure stack with type Int:
      class StackInt{ 
        var elements = [Int]() 
 
      func push(element:Int) 
      { 
        self.elements.append(element) 
      } 
      func pop() ->Int 
      { 
        return self.elements.removeLast() 
      } 
      func isEmpty()->Bool 
      { 
        returnself.elements.isEmpty 
      } 
    } 
 
    var stack1 = StackInt() 
    stack1.push(5)    // [5] 
    stack1.push(10)  //[5,10] 
    stack1.push(20) // [5,10,20] 
    stack1.pop()   // 20 
  1. Let's see the same created stack but with a generics fashion:
      class Stack <T>{ 
        var elements = [T]() 
        func push(element:T) 
        { 
          self.elements.append(element) 
        } 
        func pop()->T{ 
          return self.elements.removeLast() 
        } 
      } 
 
      var stackOfStrings = Stack<String>() 
      stackOfStrings.push("str1") 
      stackOfStrings.push("str2") 
      stackOfStrings.pop() 
 
      var stackOfInt = Stack<Int>() 
      stackOfInt.push(4) 
      stackOfInt.push(7) 
      stackOfInt.pop() 

How it works...

The first class we created, StackInt, is a stack that can work only with the Int type. It's good if you are going to use it with Int type only. However, a famous data structure like it can be used with different types, such as String or Double. It's not possible to create different stack class for each type, and here comes the magic of generics; instead we created another class called Stack marked with <T> to say it's going to deal with the generic type T, which can be Int, String, Double, and so on. Then, we create two stack instances, stackOfStrings and stackOfInt, and both share the same code as their class is built with generics.

You have been reading a chapter from
iOS Programming Cookbook
Published in: Mar 2017
Publisher: Packt
ISBN-13: 9781786460981
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime