结论:value是拷贝,Reference是引用

Value and Reference Types

Types in Swift fall into one of two categories: first, “value types”, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple. The second, “reference types”, where instances share a single copy of the data, and the type is usually defined as a class. In this post we explore the merits of value and reference types, and how to choose between them.

What’s the Difference?

The most basic distinguishing feature of a value type is that copying — the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data:

Copying a reference, on the other hand, implicitly creates a shared instance. After a copy, two variables then refer to a single instance of the data, so modifying data in the second variable also affects the original, e.g.:

The Role of Mutation in Safety

One of the primary reasons to choose value types over reference types is the ability to more easily reason about your code. If you always get a unique, copied instance, you can trust that no other part of your app is changing the data under the covers. This is especially helpful in multi-threaded environments where a different thread could alter your data out from under you. This can create nasty bugs that are extremely hard to debug.

Because the difference is defined in terms of what happens when you change data, there’s one case where value and reference types overlap: when instances have no writable data. In the absence of mutation, values and references act exactly the same way.

You may be thinking that it could be valuable, then, to have a case where a class is completely immutable. This would make it easier to use Cocoa NSObject objects, while maintaining the benefits of value semantics. Today, you can write an immutable class in Swift by using only immutable stored properties and avoiding exposing any APIs that can modify state. In fact, many common Cocoa classes, such as NSURL, are designed as immutable classes. However, Swift does not currently provide any language mechanism to enforce class immutability (e.g. on subclasses) the way it enforces immutability for struct and enum.

How to Choose?

So if you want to build a new type, how do you decide which kind to make? When you’re working with Cocoa, many APIs expect subclasses of NSObject, so you have to use a class. For the other cases, here are some guidelines:

Use a value type when:

  • Comparing instance data with == makes sense
  • You want copies to have independent state
  • The data will be used in code across multiple threads

Use a reference type (e.g. use a class) when:

  • Comparing instance identity with === makes sense
  • You want to create shared, mutable state

In Swift, Array, String, and Dictionary are all value types. They behave much like a simple int value in C, acting as a unique instance of that data. You don’t need to do anything special — such as making an explicit copy — to prevent other code from modifying that data behind your back. Importantly, you can safely pass copies of values across threads without synchronization. In the spirit of improving safety, this model will help you write more predictable code in Swift.

https://developer.apple.com/swift/blog/?id=10

swift语言点评十-Value and Reference Types的更多相关文章

  1. swift语言点评十九-类型转化与检查

    1.oc比较: -(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例 -(BOOL) isMemberOfClass: classObj 判断是否是这个 ...

  2. swift语言点评十八-异常与错误

    1.错误类型与枚举的结合 enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNee ...

  3. swift语言点评十六-Initialization && Deinitialization

    initial value:必须初始化.不影响观察者 Classes and structures must set all of their stored properties to an appr ...

  4. swift语言点评十四-继承

    Overriding A subclass can provide its own custom implementation of an instance method, type method, ...

  5. swift语言点评十五-$0

    import UIKitimport XCPlayground class ViewController: UIViewController { func action() { print(" ...

  6. swift语言点评十二-Subscripts

    Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the m ...

  7. Swift语言指南(十)--字符串与字符

    原文:Swift语言指南(十)--字符串与字符 字符串是一段字符的有序集合,如"hellow,world"或"信天翁".Swift 中的字符串由 String ...

  8. swift语言点评四-Closure

    总结:整个Closure的作用在于简化语言表述形式. 一.闭包的简化 Closure expression syntax has the following general form: { () -& ...

  9. swift语言点评二十-扩展

    结论:扩展无法修改原来的数据结构. Extensions can add new functionality to a type, but they cannot override existing ...

随机推荐

  1. P1343 地震逃生

    题目描述 汶川地震发生时,四川**中学正在上课,一看地震发生,老师们立刻带领x名学生逃跑,整个学校可以抽象地看成一个有向图,图中有n个点,m条边.1号点为教室,n号点为安全地带,每条边都只能容纳一定量 ...

  2. USACO 保护花朵 Protecting the Flowers, 2007 Jan

    Description 约翰留下了 N 只奶牛呆在家里,自顾自地去干活了,这是非常失策的.他还在的时候,奶牛像 往常一样悠闲地在牧场里吃草.可是当他回来的时候,他看到了一幕惨剧:他的奶牛跑进了他的花园 ...

  3. Sentry: Python 实时日志平台

    Links https://docs.getsentry.com/on-premise/quickstart/ https://docs.getsentry.com/on-premise/server ...

  4. ATL and MFC String Conversion Macros

    ATL 7.0介绍了一些新的转换类和宏,为现有的宏提供了重要的改进.新的字符串转换类和名称宏的形式是:C 源类型 2[C] 目标类型[EX]其中:•源类型和目标类型描述如下表.• [C]是目标类型必须 ...

  5. 分享一个完美的新闻客户端(酷商城)Android源码

    分享一个完美的新闻客户端(酷商城)Android源码,这个源码项目是从安卓教程网转载过来的,项目主要是解析html,fragment,异步缓存图片加载,webview加载网页等.可以正常的运行的,我已 ...

  6. Oracle安装后命令行中运行sqlplus / as sysdba出现错误ora-01031:insufficient privileges

    Win10安装Oracle后命令行中运行sqlplus as sysdba出现错误ora-01031insufficient privileges的解决方法 情景描述 错误样例 错误分析 解决方法 情 ...

  7. vue <router-view>没有渲染

    将routes中的components换成component

  8. Arduino扫盲(持续添加中)

    1.Arduino火的很,很大一点在于,他基本透明掉了硬件电子部分,只剩下软件部分,通过把电子部分包装成黑箱,使得大量IT人士,普通人,甚至小学生也能玩的来. 2 .Arduino是一个电子原型开发平 ...

  9. 基于vue项目的js工具方法汇总

    以下是个人过去一年在vue项目的开发过程中经常会用到的一些公共方法,在此进行汇总,方便以后及有需要的朋友查看~ let util = {}; /** * @description 日期格式化 * @p ...

  10. Sona && Little Elephant and Array && Little Elephant and Array && D-query && Powerful array && Fast Queries (莫队)

    vjudge上莫队专题 真的是要吐槽自己(自己的莫队手残写了2个bug) s=sqrt(n) 是元素的个数而不是询问的个数(之所以是sqrt(n)使得左端点每个块左端点的范围嘴都是sqrt(n)) 在 ...