swift - 为什么选择结构而不是类?

标签 swift class struct design-principles

玩过 Swift,来自 Java 背景,为什么要选择 Struct 而不是 Class?看起来它们是同一回事,Struct 提供的功能较少。为什么选择它呢?

最佳答案

根据非常受欢迎的 WWDC 2015 演讲,Swift 中面向协议(protocol)的编程(videotranscript),Swift 提供了许多使结构在许多情况下优于类的特性。

如果结构体相对较小且可复制,则更可取,因为复制比对同一个实例的多个引用(如类)更安全。当将变量传递给多个类和/或在多线程环境中时,这一点尤为重要。如果您始终可以将变量的副本发送到其他地方,您就永远不必担心其他地方会更改您下面的变量值。

有了 Structs,就无需担心内存泄漏或多个线程竞相访问/修改变量的单个实例。 (对于更具技术头脑的人来说,异常(exception)情况是在闭包内捕获结构时,因为它实际上是在捕获对该实例的引用,除非您明确地将其标记为要复制)。

类也会变得臃肿,因为一个类只能继承自一个父类(super class)。这鼓励我们创建庞大的父类(super class),其中包含许多仅松散相关的不同能力。使用协议(protocol),尤其是协议(protocol)扩展,您可以在协议(protocol)扩展中为协议(protocol)提供实现,这样您就无需类来实现此类行为。

演讲列出了首选类(class)的这些场景:

  • Copying or comparing instances doesn't make sense (e.g., Window)
  • Instance lifetime is tied to external effects (e.g., TemporaryFile)
  • Instances are just "sinks"--write-only conduits to external state (e.g.CGContext)

这意味着结构应该是默认的,类应该是后备。

另一方面,The Swift Programming Language文档有些矛盾:

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.

这里声明我们应该默认使用类,只在特定情况下使用结构。最终,您需要了解值类型与引用类型在现实世界中的含义,然后您才能就何时使用结构或类做出明智的决定。此外,请记住,这些概念总是在不断发展,Swift 编程语言文档是在面向协议(protocol)的编程演讲进行之前编写的。

关于swift - 为什么选择结构而不是类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40648765/

相关文章:

ios - UITableViewCell,设置带有多个标签的动态高度

ios - 如何在 Swift 中自动布局按钮

java - 如何实现多类应用

c++ - 用于数据存储的静态类

Swift 枚举和 NSCoding

ios - 检测何时无法正确显示 unicode 字符

python - 将列表的列表转换为对象

c# - 将 C 转换为 C#

c - 如何获取结构数组中某些结构成员的地址

c - 在不覆盖指针指向的值的情况下取消 C 中结构数组的索引