Talkin’ About My Generics — Part 1 (Swift 3)

Erica Millado
Yay It’s Erica
Published in
4 min readMar 28, 2017

Generic programming is a style of computer programming in which algorithms are written in terms of types to-be-specified-later that are then instantiated when needed for specific types provided as parameters.” — Wikipedia

Writing code with generics is a way of writing functions and data types without specifying what exact type needs to be used. Like the name suggests, generic types are not specific.

By using generics, we can write code that isn’t specific and therefore, we can abstract our code in a sophisticated manner that is cleaner and less buggy.

In this Part One post, I will discuss how Arrays, Dictionaries and Optionals are examples of generics. Part Two will discuss Writing Generic Data Classes and Structures, Writing Generic Functions and Constraining Generic Types. Part Three will discuss Associates Types and Generic Where Clauses.

Arrays as Generics

An array is an example of a generic type. An array is a container that holds any type of thing. In Swift, we have the benefit of type-inference where we can create an array without explicitly declaring its type. Since we don’t HAVE TO specify the type of any array (because it is inferred), the array as a data structure is generic.

let months = ["January", "February", "March"]

Above, I have an array of months. Since I gave the array type parameters that are strings, this months instance is given a concrete type of STRING. In other words, the type that the array should hold is defined when it’s declared.

Generic Syntax for Arrays

While the above months array doesn’t formally declare the type as STRING, there is a generic syntax way of declaring arrays as follows:

var springMonths: Array<String> = []

Note that the word Array is followed by the type in angle brackets < >. We can assign the name of our “generic type” in between these angle brackets. For generics, the norm is to use <T> as a placeholder for any generic type we reference.

Using Generic Methods on Arrays

Arrays, being generic, come with generic methods, such as .append()

springMonths.append("March")
springMonths.append("April")
springMonths.append("May")

You’ll notice above that I appended the months “March”, “April”, and “June” to the springMonths array.

What do you think will happen if I wrote this line of code next:

springMonths.append(50)

If you guessed that the compiler would give me the error:

Then you’re right! Since we declared that our Array would be of type STRING, anything that’s not a string would upset our compiler.

Dictionaries as Generics

Dictionaries are also generics because I don’t have to directly specify the type of each key or the type of each value.

For example, below, I don’t SPECIFICALLY state the dictionary type:

let monthDaysDictionary = ["January": 31, "February": 28, "March", 31, "April": 30, "May": 31, "June": 30, "July": 31, "August": 31, "September": 30, "October": 31, "November": 30, "December": 31]

However, the compiler will infer that the dictionary type will be of STRING: INT. As a result, we’ll have another type-safe data structure (meaning, only STRING: INT values can be added to this dictionary from now on).

Optionals as Generics

Remember, when retrieving any value for a given key in a dictionary, that value is returned as an optional, because that value may not exist.

let optionalMonth = Optional<String>.some("July")

Note: If you’re wondering what that .some is about, remember that optionals have two states: SOME of something or NONE of something.

To unwrap the optionalMonth above, I would do the following optional binding:

if let unwrappedOptionalMonth = optionalMonth { }

In the above unwrapping of the optional, we take the generic value of type T? and give it a generic value of type T (no question mark). This signifies that “if let” can be used with any generic type.

Arrays, Dictionaries and Optionals are all forms of generics. You can have an array of any data type you want, even objects/models that you create on your own. You can also have dictionaries of any types (keys and values), (also including objects of your own). Lastly, optionals are generic in that they all are of type T? and can be unwrapped to be of type T.

Resources:

Apple Documentation — Generics

--

--