Learn how to work with Generics in Swift and make your code more concise and powerful!

You might not know it, but you’ve probably already seen generics at work in Swift. Arrays and dictionaries are classic examples of the type safety of generics in action.

Objective-C developers are accustomed to arrays and dictionaries holding objects of many types in the same collection. This provides for great flexibility, but how do you know what an array returned from an API is meant to hold? You can only be sure by looking at documentation or at variable names, another form of documentation. Even with documentation, there is nothing (other than bug-free code!) to prevent something unexpected in the collection at runtime.

Swift, on the other hand, has typed arrays and dictionaries. An array of Ints can only hold Ints and can never (for example) contain a String. This means you can document code by writing code, allowing the compiler to do the type checking for you.

Read full article on raywenderlich.com

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">