Typealias swift что это такое

от admin

Swift typealias

The aliased name can be used instead of the existing type. It doesn’t create a new type, it simply provides a new name to an existing type.

Why use typealias

  1. Readability of our code.
  2. Combining protocols.
  3. Used with generic parameters.
  4. For declaring closures.

How to create typealias

Typealias is declared using the keyword typealias as:

Disadvantages of using typealias

  • It can become extremely messy when using typealias throughout the codebase
  • It can add an additional step when collaborating on larger projects as programmers will need to check the type

Typealias can be used with most types, e.g;

  • Built-in types: String , Int
  • User defined: class , struct , enum
  • Complex types: closures

Few exmaples of using typealias in practical iOS development

In the above Swift code typealias is being used to name a closure and use the named alias in a function argument.

In the above Swift code typealias is being used to make a delegate conform to multiple types.

In the above Swift code typealias is being used to make a simple alias for a dictionary which can be used in multiple places.

Conclusion

Initialy you may find typealias very simple, however once you dive in and take a closer look, it turns out that they’re quite capable in many cases. While over-using them could make our code base harder to navigate, making selective use of them can result into more simplified code.

Typealias usage in Swift

A typealias in Swift is literally an alias for an existing type. Simple, isn’t it? They can be useful in making your code a bit more readable. By using them in a smart way they can be really useful in your codebase.

Declaring a typealias

A typealias can be declared in Swift using the typealias keyword followed by the type you want to assign. A very simple example to understand how they can be used is by making an alias for currency, like Dollars. Take the following example of a receipt struct:

We still don’t really know the total costs as the type is just a `Double`. We can improve readability by declaring a typealias:

Which gives the receipt struct a lot more context and improves readability:

A typealias can be a simple alternative to creating a custom class or subclass.

Is a typealias a new type?

No, basically, it’s only a named alias of an existing type. Our Dollar alias is simply a Double with a different name and can, therefore, be used exactly the same as a Double .

This also works the other way around. If you would create an extension for a typealias, you’re basically creating an extension for its underlying type. The following example shows that the toEuro() method is available to both our Dollar and Double value.

Combining with generics

Generics can also be used in combination with a type alias. We could, for example, use the new Swift Result type to create an exchange result type. This could improve our readability even more:

Other valuable usage examples

A typealias is often used in projects as a way to easily reuse completion callbacks:

To make a delegate conform to multiple types:

Or, to make a simple alias for a dictionary which is used in multiple places:

A typealias can be useful to improve readability throughout your codebase as you can see. See what it can do for your project and try to make your code self documenting.

If you like to learn more tips on Swift, check out the swift category page. Feel free to contact me or tweet to me on Twitter if you have any additional tips or feedback.

Swift Typealias Overview and Examples

Learn how to define and use typealias in Swift for types, tuples, closures, protocols, and generics.

The typealias keyword in Swift defines another name for an existing type allowing a developer to add additional clarity to how an existing type is used. This post presents an overview of the typealias keyword and walks through typealias examples for various types in Swift:

Swift Typealias Keyword

The benefits of using the Swift typealias keyword fall into two main categories:

  1. Readability. Like in the Closure Typealias example, the typealias keyword in Swift can be used to shorten a verbose compound type into an easy to understand term.
  2. Clarity. Like in the Variable Typealias and Tuple Typealias examples, a Swift typealias can be used to clarify how an existing type will be used.

Check out the Swift typealias examples in this post to see how the typealias keyword can be used to improve Swift readability and clarity.

Typealias Type

A typealias type in Swift is defined using the typealias keyword followed by the name of a type:

A type, like Meters , defined using the typealias keyword can be used like any other type:

Typealias Closure

A typealias closure in Swift is defined using the typealias keyword followed by a closure definition:

Using the Swift typealias keyword to create a typealias for the closure APICompletion can help provide an easy to read and intuitive name for the complex compound closure type:

Typealias Tuple

A typealias tuple in Swift is defined using the typealias keyword followed by a tuple definition:

Typealias Protocol

A typealias protocol in Swift is defined using the typealias keyword followed by a protocol definition:

Typealias Generic

A typealias generic in Swift is defined using the typealias keyword followed by one or more placeholder types:

The Swift typealias generic Graph can then be used like other generic types:

Generic Typealias With Where Clause

A typealias generic with where clauses can be defined using the Swift keyword typealias to further disambiguate applicable types:

Typealias With Multiple Types

A typealias with multiple types is defined using the Swift typealias keyword followed by a series of types joined with & :

Swift Typealias Examples

That’s it! By using the Swift typealias keyword with generic, variable, tuple, or closure types you can make your Swift code more expressive and readable.

Swift typealias: What is it and when to use it

A type alias declaration [1] introduces a named alias of an existing type into your app. You can think of it as defining a nickname for an existing type.

How to declare a typealias

Type alias declarations are declared using the typealias keyword and have the following form:

Since typealias is just a nickname of the existing type, you can use it interchangeably everywhere in your app.

Here is an example of declaring a type alias of Int as i .

Читать:
Сколько трехзначных чисел можно составить

We can assign Int to the new i type without any problem.

What is the purpose of typealias

We use typealias to introduce a new semantic type out of the existing one.

Type aliases don't create new types. They simply allow a name to refer to an existing type.

We use this to give a more meaningful name to convey a clearer message to the reader. Let's take a look at the TimeInterval type.

In Foundation , it declares a TimeInterval type alias for a type Double .

TimeInterval gives more context to the type Double . Based on the comment, we know that the double represents the number of seconds. This gives more context to our methods and code.

Compare these two identical methods. You can tell at a glance that the first one expected a number of seconds. The later function might leave you wondering what argument the method expects; it can be seconds, minutes, or hours.

You can see that even the above example from Foundation is still based on some preference and judgment. To know that TimeInterval is in seconds, you have to check out its document at least once.

You can just document this in the method argument without introducing a new type alias.

If you look into addingTimeInterval , it already mentioned that ti is in seconds.

Introducing a new type means everyone has to check out its definition to see what it is. Since there are many date functions in the framework, the cost of introducing a new type alias might benefit users of the framework in the long run. You can understand at a glance without looking into a document that argument is expecting seconds.

This is the trade-off you have to consider before introducing a new type.

When should I use typealias

In general, a typealias function is to repurpose an existing type by giving a new name to it.

With great power comes great responsibility.

Like every language feature, you should know when to and shouldn't use it. Use a typealias too much, and you might confuse your teammate or your future self. You have to find a balance for yourself.

I can't tell you when you should use it. The best I can do is show you some scenarios. So, you can judge for yourself when and where you want to introduce new type alias.

Domain-specific type

If you have a domain-specific module, you might want to declare a new name to an existing type to convey a clearer message for your domain. We have already seen this in the previous example with TimeInterval .

Here is an example where typealias is used for a Mathematic domain.

And another example from CoreLocation .

Anonymous types/functions

By anonymous [2] , I mean a function/type without a name. Closure and Tuple fall into this category.

Closure

Here are some examples of closure you usually see in methods with a callback.

Just like a built-in type, you can make typealias over a closure.

This makes the purpose of a callback clearer, and I think it greatly improves readability. Here is a comparison between the two versions.

I have a hard time understanding closure in a method signature, especially with an optional closure. Type alias really helps me in this area.

Tuple

If you use Tuple, you can also give it a name that also improves readability. But if you need to do this for your tuple, you might consider promoting your tuple to a proper struct or class.

Shorter name for associatedtype

Inside a protocol declaration, a type alias can give a shorter to associatedtype .

Here is an example from the Sequence protocol, which exposes the underlying Element type from IteratorProtocol for easy access.

We can easily refer to Element directly from Sequence .

Shorter name for nested types

You can use a type alias to create a shorter name for a nested type.

Group multiple protocols

You can use a type alias to combine multiple protocols into one.

For example, the Codable protocol includes both Decodable and Encodable together.

Generic types

A type alias can use to provide concrete types for some or all of the generic parameters of the existing type.

For example, I declare a new Result type for my API call. In this case, I provide a concrete type of Error parameter of Result<Success, Failure> .

Here is another example where I provide concrete types for all of the generic parameters.

Conclusion

A type alias is a powerful tool. It gives you the ability to give a nickname or synonym to an existing type, giving a more meaningful name to convey a clearer message to the reader.

Everyone has to check out for a definition of the type when they first encounter the type. This might cause unnecessary overhead and confusion. But if you use the new type many places in your code, the benefit might outweigh the overhead.

This is the thing that you have to consider when adopting a type alias.

A declaration introduces a new name or construct into your program. For example, you use declarations to introduce functions and methods, to introduce variables and constants, and to define enumeration, structure, class, and protocol types. You can also use a declaration to extend the behavior of an existing named type and to import symbols into your program that are declared elsewhere. https://docs.swift.org/swift-book/ReferenceManual/Declarations.html ↩︎

You may also like

  • How to use UIKit in SwiftUI 30 Jun 2019
  • What is a Property Wrapper in Swift 26 Apr 2021
  • How to set custom CodingKey for the convertFromSnakeCase decoding strategy 06 Sep 2021
  • How to use DateFormatter in Swift 20 Dec 2020
  • Setting default values for NSUserDefaults 30 Sep 2020
  • Getting the number of days between two dates in Swift 02 Nov 2020

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

If you use Proxyman with a Flutter app, you might not see any traffic from your Flutter Project. Here is how to fix it.

There might be several reasons that cause this error. I will share the solution that works for me.

Похожие статьи