swift中为什么要存在结构体?

发布于 2022-09-01 12:51:08 字数 48 浏览 18 评论 0

RT
不考虑c/objc的话,为什么swift中要设计结构体这种存在?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

只是我以为 2022-09-08 12:51:08

struct是值传递的,class是引用传递的。

帅气尐潴 2022-09-08 12:51:08

You can use both classes and structures to define custom data types to use as the building blocks of your program’s code.

However, structure instances are always passed by value, and class instances are always passed by reference. This means that they are suited to different kinds of tasks. As you consider the data constructs and functionality that you need for a project, decide whether each data construct should be defined as a class or as a structure.

As a general guideline, consider creating a structure when one or more of these conditions apply:

  • The structure’s primary purpose is to encapsulate a few relatively simple data values.
  • It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
  • Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
  • The structure does not need to inherit properties or behavior from another existing type.

Examples of good candidates for structures include:

  • The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
  • A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
  • A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.

In all other cases, define a class, and create instances of that class to be managed and passed by reference. In practice, this means that most custom data constructs should be classes, not structures.

药祭#氼 2022-09-08 12:51:08

结构体用来存储简单数据结构用的,比如坐标系的数据结构,几何图形的数据结构等。因为它的存在使你可以不用class去存储很low的数据结构,在使用时也会很简单粗暴的值传递,少了class的复杂性。

上课铃就是安魂曲 2022-09-08 12:51:08

对于相同数据类型的数据,我们可以使用数组来表示,然而对于有不同数据类型的一组数据就不能使用数组,那用什么呢?所以有了结构体。结构体定义在栈中,或者作为对象的属性存在堆中。而对象存在于堆中。如果接触过c++,C++中有两种对象,一种是栈对象,另一种是堆对象。C++中对象和结构体就非常相似了。

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文