Hidden feature: typealias


You’re more of a video kind of person? I’ve got you covered! Here’s a video with the same content than this article 🍿


There’s a good chance that you’ve already used a typealias at one point or another.

But did you know that typealias has a hidden feature?

Let’s consider this simple typealias:

We use it to conveniently store the coordinates of a Point using a tuple.

But notice how the type of the coordinates is hardcoded:

If we try to set the coordinates using Double rather than Int, the code won’t build.

And that’s when this hidden feature of typealias comes into play!

Just like a struct or a class, a typealias can also declare generic arguments.

And thanks to this generic argument, we can now use our typealias to set the coordinates of a Point using either Int or Double.

Even better, we can also add a generic constraint to the generic argument, in order to restrict it to numerical types.

A really great use case for this feature is when you need to deal with legacy code, that implements asynchronous operations using completionHandlers.

In that situation, you can define a generic typealias that matches the signature of the completionHandler

…which will allow you to make this legacy code a bit more readable.

That’s all for this article, I hope you’ve enjoyed learning this new trick!

Here’s the code if you want to experiment with it:

typealias Point<T: Numeric> = (x: T, y: T)

let pointUsingInt = Point(x: 1, y: 2) ✅

let pointUsingDouble = Point(x: 3.0, y: 4.0) ✅

let pointUsingString = Point(x: "a", y: "b") ❌

typealias CompletionHandler<T> = (Result<T, Error>) -> Void

func fetchData(_ completion: @escaping CompletionHandler<​Data​>) {
    // ...
}
Previous
Previous

Did you know that Xcode has a search history? 💡

Next
Next

Swift has more formatters than you think! 🤯