5 Ways To Use Type Alias in Swift

5 Ways To Use Type Alias in Swift

As a developer while writing code you battle with yourself to balance between readability and being concise. Having code which is verbose always add up to readability and eventually better understanding. Being verbose definitely helps someone new on the team. But on the other hand, being less verbose you have a precise code. To maintain this balance we could leverage some of the language features like type alias that swift provides. There are different scenarios in which we can use type alias.

Type Alias Combining Protocols

We use protocol a lot while developing in swift. Protocols gives a great way to make our code modular. So take an example of JSON model parsing which I am sure every dev run in to. When we make our models in swift we usually end up making our models conforming to Codable. Let take a look at this example

struct Employee:BuildingAccess {

    var name:String

    var age:String

}

If you see above, Employee models conforms to Codable. Lets try to check definition of codable, you will find it is typealias which combines two protocols Encodable and Decodable, and looks something like this

public typealias Codable = Decodable & Encodable

This is a type alias provided by swift language for its own protocol. We can make our custom type alias for combining our custom made protocols in same way.

protocol CafeteriaAccess {

}
protocol LabAccess {

}
typealias BuildingAccess = CafeteriaAccess & LabAccess

struct Employee:BuildingAccess {

    var name:String

    var age:String
}

Type Alias Semantics Primitive Types

Adding semantics is very useful while writing code. It can add lot of clarity to code which makes it easier to follow. Typealias done in balanced way can really makes a huge difference while working with primitive types. We use primitive type like String, Int, Double in lot of our method/function signature. The primitive type doesn't convoy the usage of that parameter at all, we kind of rely on method signature of argument name to add clarity. It would really nice if our argument type can add some value too. Lets take an example

func heatProduced() ->Double {

    return 0

}

The method above headProduced gives output in form of doubles. But say now if we make a typealias Jules for Double in this context it will look something like this

typealias Jules = Double

func heatProduced() ->Jules {

    return 0

}

With that small change now we have additional context which adds to clarity.

Type Alias Generics

Type Alias can be used with generic parameters too. Lets see by an example below

typealias EventList<T> = Array<T>
let array:EventList = EventList(arrayLiteral: 1,2,3)

So we declare a typealias array called EventList which is basically array of generic type. By using typelias as event list you have made it very clear the nature of that list. We can take this step further by adding constraint to generic parameters of our alias type. For eg

typealias EventList<T> = Array<T> where T:StringProtocol

This is very useful when we want to define array of custom types without even subclassing them.

Type Alias Associated Type Protocols

Associated type in protocols also benefits from type alias. Details of this goes beyond the scope of this article. Lets take a look at the example

protocol Example {

 associatedtype load: StringProtocol

}
struct Implement: Example {

    typealias load = String

}

Type Alias Closure

Let's say we have a function of upload, that can emit 3 possible outcomes. Lets look at an example below

func upload(success: ((Int) -> Int)?,

            failure: ((Error) -> Void)?,

            progress: ((Double) -> Void)?)
}

If you see the example above you see a lot of parentheses and it looks little ugly. We can make use of type alias here as follows.

typealias Success = (Int) -> Int

typealias Failure = (Error) -> Void

typealias Progress = (Double) -> Void

func upload(success: Success?, failure: Failure?, progress: Progress?) {
}

Now the upload function looks much better.

Conclusion

TypeAlias seems to really useful, but there are certain drawbacks too. Especially for someone who is new to your code base, it might take a little time to understand things. You always have a to draw a line between good usage and overboard. I use typealias all the time but try to have some sanity around it. Just curious how you use type alias in your day to day work. Please mention your experience and thoughts in the comments.