加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 为什么选择struct over类?

发布时间:2020-12-14 06:22:57 所属栏目:百科 来源:网络整理
导读:使用Swift,来自Java背景,为什么要选择一个Struct而不是一个类?看起来他们是一样的东西,一个Struct提供较少的功能。为什么选择呢? 根据在Swift( video, transcript)中非常流行的WWDC 2015谈论面向协议的编程,Swift提供了许多功能,使结构比类在许多情
使用Swift,来自Java背景,为什么要选择一个Struct而不是一个类?看起来他们是一样的东西,一个Struct提供较少的功能。为什么选择呢?
根据在Swift( video, transcript)中非常流行的WWDC 2015谈论面向协议的编程,Swift提供了许多功能,使结构比类在许多情况下更好。

如果结构体相对较小并且可复制,则结构体是优选的,因为复制比对类具有对同一实例的多个引用更安全。这在将变量传递到许多类和/或在多线程环境中时尤为重要。如果你总是可以发送你的变量的副本到其他地方,你永远不必担心那个其他地方改变你下面的变量的值。

使用Structs,更少需要担心内存泄漏或多线程访问/修改变量的单个实例。 (对于更技术上的头脑,例外是当捕获一个闭包内的结构,因为它实际上是捕获到实例的引用,除非你明确标记它被复制)。

类也可能变得blo肿,因为类只能从单个超类继承。这鼓励我们创造巨大的超类,包括许多不同的能力,只是松散相关。使用协议,尤其是协议扩展,您可以为协议提供实现,允许您不需要类来实现这种行为。

该讲述阐述了这些场景,其中类是首选:

  • 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编程语言文档是在面向协议编程之前编写的。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读