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
Mastering Swift 3

You're reading from   Mastering Swift 3 Build incredible apps for iOS and OS X

Arrow left icon
Product type Paperback
Published in Oct 2016
Publisher Packt
ISBN-13 9781786466129
Length 392 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Jon Hoffman Jon Hoffman
Author Profile Icon Jon Hoffman
Jon Hoffman
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Preface 1. Taking the First Steps with Swift FREE CHAPTER 2. Learning About Variables, Constants, Strings, and Operators 3. Using Swift Collections and the Tuple Type 4. Control Flow and Functions 5. Classes and Structures 6. Using Protocols and Protocol Extensions 7. Protocol-Oriented Design 8. Writing Safer Code with Availability and Error Handling 9. Custom Subscripting 10. Using Optional Types 11. Working with Generics 12. Working with Closures 13. Using Mix and Match 14. Concurrency and Parallelism in Swift 15. Swift Formatting and Style Guide 16. Swifts Core Libraries 17. Adopting Design Patterns in Swift

When not to use generics

One of the things that we should watch out for while using generics is to avoid using them when we should be using protocols. This is, in my opinion, one of the most common misuses of generics in other languages. Let's take a look at an example so that we know what to avoid.

Let's say that we define a protocol called WidgetProtocol, which is as follows:

protocol WidgetProtocol { 
    //Code 
} 

Now, let's say that we want to create a custom type (or function) that will use various implementations of the WidgetProtocol protocol. I have seen a couple of instances where developers have used generics with a type constraint to create custom types as follows:

class MyClass<T: WidgetProtocol> { 
    var myProp: T? 
    func myFunc(myVar: T) { 
        //Code 
    } 
} 

While this is a perfectly valid use of generics, it is recommended that we avoid implementations like this. It is a lot cleaner and easier to read if we use WidgetProtocol without generics...

lock icon The rest of the chapter is locked
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