swift 类型别名作用_在Swift中使用类型别名的5种方法

swift 类型别名作用

Writing code is a battle between readability and being concise. Verbose code increases readability and eventually better understanding. Being verbose definitely helps those new to the team. On the other hand, being less verbose means you have more precise code. To maintain this balance we can leverage some of the language features, like typealias, that Swift provides. There are various different scenarios in which we can use type alias.

编写代码是在可读性和简洁之间的斗争。 详细的代码提高了可读性,并最终更好地理解了代码。 冗长无疑有助于团队中的新手。 另一方面,不那么冗长意味着您拥有更精确的代码。 为了保持这种平衡,我们可以利用Swift提供的某些语言功能,例如typealias。 在多种情况下,我们可以使用类型别名。

Typealias组合协议 (Typealias Combining Protocols)

We use protocols a lot while developing in Swift. Protocols are a great way to make our code modular. Take the example of JSON model parsing, which I’m sure every dev has run into. When we make our models in Swift we usually end up making our models conforming to Codable. Let’s take a look at this example:

在Swift中进行开发时,我们经常使用协议。 协议是使我们的代码模块化的好方法。 以JSON模型解析为例,我敢肯定每个开发人员都会遇到。 当我们在Swift中创建模型时,通常最终会使模型符合Codable。 让我们看一下这个例子:

struct Employee:BuildingAccess {var name:Stringvar age:String}

As you can see above, the Employee model conforms to Codable. Let’s try to check the definition of codable. You’ll find it’s typealias, which combines two protocols, Encodable and Decodable, and looks something like this:

正如您在上面看到的, Employee模型符合Codable。 让我们尝试检查可编码的定义。 您会发现它是typealias ,它结合了两个协议EncodableDecodable ,看起来像这样:

public typealias Codable = Decodable & Encodable

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

这是Swift语言为其自身协议提供的类型别名。 我们可以创建自定义类型别名,以相同的方式组合自定义协议。

protocol CafeteriaAccess {}protocol LabAccess {}typealias BuildingAccess = CafeteriaAccess & LabAccessstruct Employee:BuildingAccess {var name:Stringvar age:String}

类型别名语义基本类型 (Type Alias Semantics Primitive Types)

Adding semantics is very useful when writing code. It can add a lot of clarity to code, making it easier to follow. Typealias, when done in a balanced way, can make a huge difference when working with primitive types. We use primitive types like String, Int, and Double in many of our method/function signature. The primitive type doesn’t convoy the usage of that parameter at all, we kind of rely on the method signature of the argument name to add clarity. It would be nice if our argument type could also add some value. Let’s look at an example:

编写代码时,添加语义非常有用。 它可以为代码增加很多清晰度,使其更易于遵循。 如果以平衡的方式完成Typealias,则在使用基本类型时会产生巨大的不同。 在许多方法/函数签名中,我们使用诸如StringIntDouble类的原始类型。 原始类型根本不鼓励使用该参数,我们有点依赖参数名称的方法签名来增加清晰度。 如果我们的参数类型也可以添加一些值,那就太好了。 让我们看一个例子:

func heatProduced() ->Double {return 0}

The method above, headProduced, gives the output in the form of doubles. But say we make a typealias, Jules, for Double in this context — it will look like this:

上面的方法headProduced给出了double形式的输出。 但是,在这种情况下,请说我们为Double做一个类型别名Jules ,它看起来像这样:

typealias Jules = Doublefunc heatProduced() ->Jules {return 0}

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

有了很小的更改,我们就拥有了更多的上下文,从而使内容更加清晰。

类型别名泛型 (Type Alias Generics)

Type Alias can be used with generic parameters too. Let’s take a look at an example:

类型别名也可以与通用参数一起使用。 让我们看一个例子:

typealias EventList = Arraylet array:EventList = EventList(arrayLiteral: 1,2,3)

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

因此,我们声明了一个称为EventList的类型别名数组,该数组基本上是通用类型的数组。 通过使用typelias作为事件列表,您可以使该列表的性质非常清楚。 通过向别名类型的通用参数添加约束,我们可以进一步迈出这一步。 例如:

typealias EventList = Array where T:StringProtocol

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

当我们想要定义自定义类型的数组甚至不将其子类化时,这非常有用。

类型别名关联的类型协议 (Type Alias Associated Type Protocols)

Associated type in protocols also benefits from type alias. The full details of this are beyond the scope of this article. Let’s take a look at an 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 three possible outcomes. Let’s take a look at an example:

假设我们具有上传功能,可以发出三种可能的结果。 让我们看一个例子:

func upload(success: ((Int) -> Int)?,failure: ((Error) -> Void)?,progress: ((Double) -> Void)?) {}

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

如果您看到上面的示例,则会看到很多括号,并且看起来很丑陋。 我们可以在这里使用类型别名,如下所示:

typealias Success = (Int) -> Inttypealias Failure = (Error) -> Voidtypealias Progress = (Double) -> Voidfunc upload(success: Success?, failure: Failure?, progress: Progress?) {}

Now the upload function looks much better!

现在,上传功能看起来更好了!

结论 (Conclusion)

TypeAlias seems really useful, but it also has certain drawbacks. Especially for someone who’s new to your codebase, it might take a little time to understand things. You always have to draw a line between good usage and going overboard. I use typealias all the time but I try to have some sanity around it.

TypeAlias看起来确实很有用,但它也有某些缺点。 特别是对于您的代码库的新手来说,可能需要一点时间来理解。 您总是必须在良好用法和过度使用之间划清界限。 我一直都在使用typealias,但是我尽量保持理智。

I’m curious how you use typealias in your day-to-day work. Please talk about your experiences and thoughts in the comments.

我很好奇如何在日常工作中使用打字别名。 请在评论中谈论您的经历和想法。

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/better-programming/5-ways-to-use-type-alias-in-swift-45ddce3cc941

swift 类型别名作用

你可能感兴趣的:(java,python,swift,ios,leetcode)