Generic Enums

Introduction

Welcome to Lesson 6 of Advanced Enum. Chapter 1, you’ve learned how to create generic structs, classes, and functions. In Chapter 5, you’ve learned how to create generic protocols using associated types. In this lesson, you will learn how to create generic enums. When you hear the term generic, you already know the purpose. It is to provide scalable and reusable code, following the principle of DRY.

Problem

A little more complex associated value

Introducing Generic Enums

Like structs, classes, and functions, the syntax looks identical.

  1. enum Information<T, U> {
  2. case name(T)
  3. case website(T)
  4. case age(U)
  5. }

Let us initialize.

  1. Information.name("Bob") // Error

The compiler is able to recognize T as String based on “Bob”. However, the type of U is not defined yet. Therefor, you must define both T and U explicitly as shown below.

  1. Information<String, Int>.age(20)

Optionals with Enum

option-click on Optional. It is an enum with associated value defined as T. There are two ways to create optional types: 1. Traditional 2. Native

  1. // Traditional
  2. let explicitOptionals = Optional("Bob")
  3. // Native
  4. let quickOptionals: String? = "Bob"
  5. print(explicitOptionals) // Optional("Bob")
  6. print(quickOptionals) // Optional("Bob")

Custom Optionals

Let us attempt to create our own “optional” type.

  1. enum MyOptional<T> {
  2. case none // nil
  3. case some(T)
  4. init(_ anyValue: T) {
  5. self = MyOptional.some(anyValue)
  6. }
  7. }

Let us initialize

  1. MyOptional("Bobby")

Safe unwrapping for MyOptional does not work. TheOptional enum probably has its own custom operators.

  1. if let value = MyOptional {
  2. print(value)
  3. } // Error

Source Code

7006_generic_enum.playground

Conclusion

You’ve learned how to create generic enums with associated value which allows enums like Optional to convert any type into its own optional type. If you have two or more non-concrete types such as T and U, make sure you explicitly define them.

In the following lesson, you will learn how error handling was done in the past with generic enums.

Note: Learn Swift with Bob is available on Udemy. If you wish to receive a discount link, you may sign up here.