Daniel's working notes

Using enum for polymorphism

Sometimes when working with Swift, we need to deal with collection of different types. For example, we can deal with array that contains int, string or bool together. Since array the element of array containing multiple types, we resort to [Any] for its type.

The problem with [Any] is that we don’t know what’s the element represent at the compile time. Sure we can define logic to run at the compile time but it also has risk to crash the application or lead to bugs.

Here we can use enum to model polymorphism. Let’s say, we want to use Array that contains Date and range of Date

We can define an enum like so:

enum DateType {
	case date(Date)
	case range(Range<Date>)
}

then we can use it in array to store DateType

let dates: [DateType] = [
	DateType.date(Date()),
	DateType.date(Date()...Date(timeIntervalSinceNow: 7200))
]

Linked Notes: