How to use typealias in swift ?

typealias also known as type-Identifier. so basically we are defining a substitute of a type. For example we can give type of String to Str as – typealias Str = String so now onwards you can use Str instead of String

1. Basic Example with data type

typealias Str = String
let x: Str = "Boom"
print(x) // prints Boom

You might thinking what’s the big thing in it? But it is. Let suppose you have a complex statement like closure etc so you can shrink it down with substitute so your code will look much cleaner, let me explain you with example :

2. typealias with closure:

typealias customBlock =  (([String:String])->Void)

func signIn(userID:String, completion: @escaping customBlock) {
    completion(["Name": "Jhon Cena"])
}

signIn(userID: "11") { dataObject in
    print(dataObject)
}

So here we have used customBlock which act as as typealias which declare as a closure. So you might required same block in your project which can be replace shorter. In this way this can easily readable & reduce code density. like wise you can try with Result<DataObj, Error> for your network call modules.

3. Multiple Protocols with typealias:

typealias multipleProtocol = NSObjectProtocol & NSCopying & NSCoding
var xValue: multipleProtocol

Here we have used multiple protocols with typealias, so you can just use multipleProtocol which act as a NSObjectProtocol & NSCopying & NSCoding.. much cleaner huh!! 😤😤

Leave a Comment

Your email address will not be published. Required fields are marked *