Whether or not type aliases are syntactic sugar or provide more code clarity, is a common source of debate among developers. While being able to write code in a more concise manner, it can also sometimes make the result harder to read and maintain.
Semantic types
Take Foundation’s TimeInterval type as an example. Whenever we see a time interval, we know that we’re dealing with time, which wouldn’t be true if a “raw” number type like Double was used instead. However, it turns out that TimeInterval is actually not a brand new type, and is in fact just a type alias for Double
typealias TimeInterval = Double
Using a type alias like that has pros and cons. Since TimeInterval isn’t actually its own type, but rather just an alias — it means that all Doublevalues are valid TimeInterval values, and vice versa. The downside of that is that we don’t get that extra compile time safety that we would if we were creating a brand new type instead, but on the other hand, the benefit is that any Double method (including operators) can also be used on TimeInterval values — reducing the need for code duplication and boilerplate.
Generic closure aliases
Finally, let’s take a look at how type aliases can be used to create generic shorthands for closures. For example, if our code base makes heavy use of a Result type to model various results of asynchronous operations — we might want to define a shorthand for a closure that takes such a result, which is what we’ll most likely use for lots of our completion handlers:
typealias Handler = (Result) -> Void
Now, whenever one of our functions accepts a completion handler, we can simply use our above Handler type and specialize it with whichever result that we’ll be passing into that handler — like this:
func searchNotes(matching query: String,
then handler: @escaping Handler) {
...
/code>
