Thumbs up comments, feel useful friends can pay attention to the author public number iOS growth refers to north, continue to update

Semantically, Typealias in Swift is an alias for an existing class. When we talk about language features in Swift, Typealias tends to be a bit of an understatement.

Referring to TypeAliases, a simple function is to add aliases to existing classes. To ease the reading and maintenance burden, we use aliases as types for instances of specific uses:

import UIKit

typealias Location = CGPoint
typealias distance = Double
Copy the code

Sure, this works a bit, but just adding an alias may not be that useful to you!

Today we’ll take a closer look at Typealias in Swift. In a clever way, it can be very useful in your code base.

Hopefully, this will be dry enough.

Learning goals

Through the completion of this study, we mainly solve the following problems

  1. What is Typealias? Is Typealias a new type?
  2. As a practical matter, what problems can we solve with Typealias?

Typealias

Typealias is, as the name implies, an alias for a specific type. Using the TypeAlias keyword allows you to assign a new name to an existing type just as you would with a normal assignment statement.

typealias Dollar = Double
Copy the code

When we define the price of a product, we define the price type as Dollar instead of Double. When we need to define a price, we use Dollar.

let price: Dollar = 0.0
Copy the code

Typealias is a simple alternative to creating custom classes or subclasses.

Is Typealias a new type?

So is Typealias a new type? No, basically, this is just a named alias for an existing type. Our Dollar alias is just a Double with a different name, which is used in exactly the same way as Double.

And vice versa. If you create an extension for a Typealias, you are basically creating an extension for its underlying type.

Many of the classes we use in Swift are Typealias. Such as:

#if CLR || JAVA
	public typealias Int = Int64
	public typealias UInt = UInt64
#elseif ISLAND
	#if CPU64
	public typealias Int = Int64
	public typealias UInt = UInt64
	#elseif CPU32
	public typealias Int = Int32
	public typealias UInt = UInt32
	#else
	#hint Unexpected bitness
	public typealias Int = Int64
	public typealias UInt = UInt64
	#endif
#elseif COCOA
	public typealias Int = NSInteger
	public typealias UInt = NSUInteger
#endif
.
public typealias Any = protocol<> //Dynamic;
public typealias AnyObject = protocol<> //Dynamic;
#if CLR
public typealias AnyClass = System. `Type`
#elseif COCOA
public typealias AnyClass = rtl.Class
#elseif JAVA
public typealias AnyClass = java.lang.Class
#endif
Copy the code

Isn’t that a lot like the typedef keyword in C?

Typealias Practice Guide

I’ll show you a few typeAliases in Swift in action.

readability

As we said at the beginning, using Typealias reduces the reading and maintenance burden. Typealias can give code more meaning. Of course, this is not always necessary. For a function definition, the parameter of the function clearly indicates the type of the parameter,

func orderDonuts(amount: Int){}Copy the code

Declaring a Typealias then incurs additional overhead.

For variables and constants, on the other hand, it can generally improve readability and greatly improve documentation.

Simplify closure parameters

We know that functions in Swift support closure arguments, and the most common use of closure arguments is the trailing closure.

func handle(action: (Int) - >Int) { . }
Copy the code

This is still fairly neat, but when we define multiple closure parameters, it can seem confusing

func handle(success: ((Int) - >Int)?.failure: ((Error) - >Void)?.progress: ((Double) - >Void)?){}Copy the code

This is where Typealias comes in handy.

typealias Success = (Int) - >Int
typealias Failure = (Error) - >Void
typealias Progress = (Double) - >Void

func handle2(success: Success? .failure: Failure? .progress: Progress?). { . }
Copy the code

And of course you could say this is another extension of readability, just like in Objective-C when we’re defining blocks, we’re used to declaring a name just so we can use it.

When we need to use this composite type of data in multiple methods, or when we need to use it as an attribute, for subsequent use:

typealias Success = (Int) - >Int
typealias Failure = (Error) - >Void
typealias Progress = (Double) - >Void

class MyHttpManager {
    var successHandler:Success?
    var failureHandler:Failure?
    / /...
    func foo(success: Success.failure: Failure) {
        if isSuccess {
            success()
        } else {
            failure()
        }
    }

    func bar(success: @escaping Success.failure: @escaping Failure) {
        successHandler = success
        failureHandler = failure
        internalHandle()
    }
    // ...
    func internalHandle(a) {
        / /...}}Copy the code

Combine with generics

Typealias can also be used in conjunction with generics.

During a network request, our callback function always carries some information about the current network request for our Debug process.

We can further improve on our examples above by using generic handlers:

typealias Handler<Number> = (Number.HTTPResponse? .Context) - >Void

typealias Success = Handler<Int>

typealias Failure = Handler<Error>

typealias Progress = Handler<Double>


class MyManager {
    var successHandler:Success?
    var failureHandler:Failure?
    / /...
    func foo(success: Success.failure: Failure) {
        if isSuccess {
            success()
        } else {
            failure()
        }
    }

    func bar(success: @escaping Success.failure: @escaping Failure) {
        successHandler = success
        failureHandler = failure
        internalHandle()
    }
    // ...
    func internalHandle(a) {
        / /...}}Copy the code

In this way, we define Success, Failure, and Progress to deliver more data

This approach is also useful for your own type. You can create a generic definition and then define a detailed Typealias:

enum Either<Left.Right> {
   case left(Left)
   case right(Right)}typealias Result<Value> = Either<Value.Error>

typealias IntOrString = Either<Int.String>
Copy the code

With the yuan zu

Similarly, you can use generics and tuples to define types without having to define a Struct.

typealias TypedUserInfoKey<T> = (key: String, type: T.Type)

let integerTypedKey = TypedUserInfoKey(key: "Foo", type: Int.self)
Copy the code

Just as we declare a structure, we seem to declare a progenitor with a one-by-one member constructor.

Combination of agreement

Sometimes there are multiple protocols, and there is a specific type that needs to implement them all.

For example, the Codable protocol in Swift is the Typealias for Decodable and Encodable protocols:

typealias Codable = Decodable & Encodable
Copy the code

By combining protocols in this way, our code is more readable. Another example is:

/ / manned
protocol CarriesPassengers {}/ / cargo
protocol CarriesCargo {}/ / land
protocol OnRoad {}/ / water
protocol OnWater {}/ / car
typealias Car = CarriesPassengers & CarriesCargo & OnRoad
/ / ship
typealias Boat = CarriesPassengers & CarriesCargo & OnWater
Copy the code

We can combine functions to implement different class definitions, which is a good way to decouple them.

The attribute

We covered the use of association types in protocols in Day11 – Protocols and Extensions.

protocol Identifiable {
    associatedtype ID: Equatable & CustomStringConvertible
    var id: ID { get}}struct Book: Identifiable {
    let id: String
}

struct clothes: Identifiable {
    let id: Int
}
Copy the code

When we do not want to declare a usage that follows an association type in the protocol, we can use Typealias to do so

protocol Identifiable {
    associatedtype ID: Equatable & CustomStringConvertible
}

struct Book: Identifiable {
    typealias ID = String
    
    let id: ID
}

struct clothes: Identifiable {
    typealias ID = Int
    
    let id: ID
}
Copy the code

conclusion

The primary goal of Typealias is probably to make your code more readable. But its use in combination with generics and tuples may surprise you.

So when you use compound types, you definitely notice the benefits of Typealias. But be careful not to let your alias get in the way.


If you have any questions, comments or feedback, please feel free to contact me. If you wish, you can spread the word by sharing this article.

Thank you for reading this! 🚀