Generics in typealias

Swift

Use a generic type in type aliases to increase code reusability. Notice how the same type alias is used for all Post, [Post], and [Book] 😎

While type aliasing is a simple concept of Swift, that is literally just an alias for an existing type, it can be used in intersting ways to make the code more readable.

Think about how Apple has a typealias TimeInterval = Double, it does not only increases readability, but also serves as a note that this could be something else other that a Double in the future –Maybe?–

Coming from ObjC, type aliasing can be useful to remove some of the old prefixes and making the code a bit Swifter!

final class Service { typealias Book = SLBSomeLibraryServiceBookModel func loadBooks() -> [Book] { // ... } }

Combining type aliasing with generics is another nice way to increase readability and reusability:

enum APIError: Error { // ... } struct Post { // ... } struct Book { // ... } struct Service { typealias Handler<Response> = (Result<Response, APIError>) -> Void func fetchPost(id: Int, _ completion: Handler<Post>) { // ... } func fetchPosts(_ completion: Handler<[Post]>) { // ... } func fetchBooks(_ completion: Handler<[Book]>) { // ... } }

Antoine van der Lee wrote a nice blog post with more details, give it a read if you find the topic intersting.