swift 两数相加 分析_让我们剖析泛型和Swift中Any类型之间的区别

swift 两数相加 分析

Swift is one of the topmost type-safe languages nowadays. ???

Swift是当今最顶级的类型安全语言之一。 ???

哦,等等! 语言是类型安全的,这意味着什么? (Ohhh wait!! What does it mean if a language is type-safe? ?)

A type-safe language always ensures that an operation works with the right kind of data available at that point.✓

类型安全的语言始终确保操作可以处理当时可用的正确数据。✓

If a language has the ability to declare different data types (e.g., Int, Float, String, Array, Dictionary) and it has also the ability to ensure that a variable that is declared with a particular data type will never hold a different kind of data, then it is called a type-safe language.

如果一种语言能够声明不同的数据类型(例如,Int,Float,String,Array,Dictionary),并且还能够确保使用特定数据类型声明的变量永远不会拥有不同类型的数据,那么它被称为类型安全语言。

In type-safe languages, type checking is always done. It may happen in compile time or run time depending on the language.✅

在类型安全的语言中,始终执行类型检查。 根据语言的不同,它可能在编译时或运行时发生。

现在,Swift中的泛型是什么? (Now, what are Generics in Swift??)

Generics are type safe, and help us write flexible, reusable functions and types. Using Generics, we can write code that works for all data types. Since Swift is a type-safe language, without breaking this we are able to write generic codes that can avoid code duplication.

泛型是类型安全的,可以帮助我们编写灵活,可重用的函数和类型。 使用泛型,我们可以编写适用于所有数据类型的代码。 由于Swift是一种类型安全的语言,因此只要不破坏它,我们就可以编写可避免代码重复的通用代码。

Let’s take a simple example: an Array is an ordered collection which can hold the same type of data. That’s why in the definition of an Array, we can see that it takes a generic type of Element. Hence an Array becomes a generic type of Collection.

让我们举一个简单的例子:一个数组是一个有序集合,可以保存相同类型的数据。 这就是为什么在Array的定义中,我们可以看到它采用Element的通用类型 因此,数组成为Collection通用类型

Ok. Cool. Then what is the Any type in Swift????

好。 凉。 那么Swift中的Any类型是什么? ???

Swift also supports the Any type. As the name indicates, it can represent an instance of any type like a struct, class, enum and function type.

Swift还支持Any类型。 顾名思义,它可以表示任何类型的实例,例如结构,类,枚举和函数类型。

那么,Objective C id和Swift的Any是否相同?(So are the Objective C id and Swift’s Any the same??)

In Swift 3, the Objective C id type maps to Swift’s Any type. This improves the compatibility of Swift and Objective C.

在Swift 3中,Objective C id类型映射为Swift的Any类型。 这提高了Swift和Objective C的兼容性。

但是如何以及为什么? (But how and why??)

In Swift 2, the Objective C id was mapped to Swift’s Any object. This worked well for most of the cases, but sometimes it resulted in unexpected behavior. One of the key concepts in Swift is Value Types, and this mapping was not doing the proper justice to this concept.

在Swift 2中,Objective C id映射到Swift的Any对象。 在大多数情况下,此方法效果很好,但有时会导致意外的行为。 Swift中的关键概念之一是值类型,并且此映射并未对此概念做适当的说明。

Swift is just a new language for iOS development, and Objective C has been around for years. So of course most of the projects were developed in Objective C only. Now in order to convert an Objective project to a Swift project, the requirement came that it should be possible to bridge any Swift type to any Objective C object.

Swift只是iOS开发的一种新语言,而Objective C已经存在了很多年。 因此,当然,大多数项目仅在目标C中开发。 现在,为了将Objective项目转换为Swift项目,要求可以将任何Swift类型桥接到任何Objective C对象。

But this was not a problem for Swift classes and Swift value types like Int, String, Float because they already have their Objective C counterparts. The problem arose for the Swift value types that did not have any Objective C counterparts.

但这对于Swift类和诸如Int,String,Float之类的Swift值类型来说并不是问题,因为它们已经有与Objective C对应的对象。 对于没有任何Objective C对应项的Swift值类型,出现了问题。

So to fix this, the Objective C id type mapped onto the Swift Any type.✅✅✅

因此,要解决此问题,可以将Objective C id类型映射到Swift Any类型。

Enough Definitions ?. Now let’s come to the main topic. By the above points, it looks like Generics and the Any type are the same. But are they really???

足够的定义吗? 现在让我们进入主要主题。 通过以上几点,看起来泛型和Any类型是相同的。 但是他们真的吗?

On a high level, Any may look similar to Generics. But let’s try to find some differences-???

从总体上讲,Any可能看起来与Generics类似。 但是,让我们尝试找到一些区别-???

We all know what a Stack is in Data Structures, right? A stack is a basic linear data structure where insertion and deletion of items takes place at one end only.

我们都知道数据结构中的堆栈 ,对吗? 堆栈是一种基本的线性数据结构,其中项目的插入和删除仅在一端进行。

Now we will implement the Stack structure in Swift. First, we will implement using Generics then with the Any type.

现在我们将在Swift中实现Stack结构。 首先,我们将使用泛型然后使用Any类型来实现。

使用泛型的堆栈实现: (Stack Implementation using Generics:)

The above Stack implementation is using Generics. The struct takes a generic type of Element item and implements a stack using that item. Now let’s do some operation with Generic Stack:

上面的Stack实现使用的是泛型。 该结构采用Element项目的通用类型,并使用该项目实现堆栈。 现在让我们对通用堆栈进行一些操作:

It declares a Generic Stack which can hold an Integer type of element. We are pushing the integer element to the stack. Up to this point, everything works great.

它声明了一个通用堆栈,可以容纳一个整数类型的元素。 我们正在将整数元素推入堆栈。 到目前为止,一切正常。

But what if I want to push a float element onto that above the genericStack?

但是,如果我想将float元素推入genericStack之上的元素该怎么办?

❌❌ Oops! Compilation Error! ❌❌

❌❌糟糕! 编译错误! ❌❌

使用Any类型的堆栈实现: (Stack Implementation using the Any type:)

In this Stack Implementation, the items array can hold Any type of element. We are not specifying about what will be the exact data type of the items array element in the definition. Now let’s do the same basic operations on this stack:

在此堆栈实现中,items数组可以容纳任何类型的元素。 我们没有指定定义中的数组元素的确切数据类型是什么。 现在让我们在此堆栈上执行相同的基本操作:

No issues, right? Everything is working fine here also. Initially, we declared a stack and pushed two integer elements into it. When we call the show() method, it prints the exact array [3, 4].

没问题吧? 这里的一切也都很好。 最初,我们声明了一个堆栈并将两个整数元素压入其中。 当我们调用show()方法时,它将打印精确的数组[3,4]。

Now let’s push a float value into it.☄️

现在让我们将浮点值推入其中.☄️

✅✅ No Error! Everything works fine! ✅✅

Error没有错误! 一切正常! ✅✅

那么幕后发生了什么? 为什么我们没有收到任何错误??? (So what is happening behind the scenes? Why we are not getting any error????)

Generics basically tells the compiler that:

泛型基本上告诉编译器:

I have declared a generic type and I am going to give you an exact type later. I want you to apply that type everywhere I specify.

我已经声明了泛型类型,稍后将为您提供确切的类型。 我希望您在指定的所有位置应用该类型。

The Any type basically tells the compiler:

Any类型基本上告诉编译器:

Don’t worry about this variable, no need to apply any type here let me do whatever I want to do.

不用担心这个变量,这里不需要应用任何类型,让我做我想做的任何事情。

Generics can be used to define flexible functions, but the types of arguments are still checked by the compiler. Any type can be used to dodge Swift’s type system.?

泛型可用于定义灵活的函数,但是参数的类型仍由编译器检查。 任何类型都可以用来闪避Swift的类型系统。

In the generic stack declaration, we are telling the compiler that the stack should take the integer type only. Then when we are trying to insert a float type of element into it, that means we are breaking that promise. Hence it is throwing a compile time error. It always expects that the element should be an integer type.

在通用堆栈声明中 ,我们告诉编译器堆栈应仅采用整数类型。 然后,当我们尝试将浮动类型的元素插入其中时,这意味着我们正在兑现承诺。 因此,它将引发编译时错误。 始终希望该元素应为整数类型。

But for the Any Stack, we are not getting any compile time or runtime error. Even if we call the show() method, it prints the stack as [3, 4, 5.0] which means the stack holds integer and float type of values. So in any stack, there is no type restriction, we can push any type of value into it (but there are possibilities of runtime exceptions).

但是对于Any Stack ,我们没有遇到任何编译时或运行时错误。 即使我们调用show()方法,它也会将堆栈显示为[3,4,5.0] ,这意味着堆栈中包含整数和浮点类型的值。 因此,在任何堆栈中都没有类型限制,我们可以将任何类型的值压入其中(但是有运行时异常的可能性)。

结论 (Conclusion)

So if we use Generics then we can write flexible functions, structures, classes, and protocols without compromising Swift’s type safety. But if we use the Any type, then we are kind of our own boss, we can do almost anything we want.

因此,如果我们使用泛型,那么我们可以编写灵活的函数,结构,类和协议,而不会影响Swift的类型安全性。 但是,如果使用Any类型,那么我们就是自己的老板,我们几乎可以做任何我们想做的事情。

??? Cheers!!! Thank you for reading!! ???

??? 干杯!!! 谢谢您的阅读!! ???

翻译自: https://www.freecodecamp.org/news/lets-dissect-the-differences-between-generics-and-the-any-type-in-swift-86c8214c35e4/

swift 两数相加 分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值