结论: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. Codeforces 994B. Knights of a Polygonal Table

    解题思路 将骑士按力量从小到大排序,到第i个骑士的时候,前面的i-1个骑士他都可以击败,找出金币最多的k个. 用multiset存金币最多的k个骑士的金币数,如果多余k个,则删除金币数最小的,直到只有 ...

  2. 使用最新vue_cli搭建的模版

    使用最新vue_cli搭建的模版,包含了常用的插件,router和axiox与测试插件.项目的结构如下: 使用之前请打开 REAMME.md 看看. 已经搭建好的框架的下载地址:https://sha ...

  3. Android 数字四舍五入

    BigDecimal b = new BigDecimal(hour).setScale(1, BigDecimal.ROUND_HALF_UP); setScale(int newScale, in ...

  4. sybase profile

    # # Sybase Product Environment variables # SAP_JRE7_32="/opt/sybase/shared/SAPJRE-7_1_011_32BIT ...

  5. 常规RPC通讯过程【转载】

    在 HTTP2 协议正式开始工作前, 如果已经知道服务器是 HTTP2 的服务器, 通讯流程如下: 客户端必须首先发送一个连接序言,其逻辑结构: PRI * HTTP/2.0\r\n\r\nSM\r\ ...

  6. Powerpivot PowerBI相关组件下载安装(附操作截图)

    加载方式:com加载项加载方法: 点击Excel界面[文件]→[选项]→[加载项]→[COM加载项]→[转到] Excel2013加载PowerView Excel216PowerQuery不需要加载 ...

  7. C++面向对象的设计思想——小结

    1 对象的概念 面向对象(Object Oriented Analysis Design,OOAD)的思想把整个世界看成是由具有某种特征行为功能的基本单元——对象构成的.OOAD把一个对象的特征称为属 ...

  8. VMware虚拟机共享文件夹

    安装好虚拟文件夹后,第二次开机时发现/mnt/hgfs目录下找不到共享的文件夹,原因是vmfg-fuse服务没有开启. 在root的配置文件中添加如下代码,设置开机自启: /usr/bin/vmhgf ...

  9. 7、A Design of Group Recommendation Mechanism Considering Opportunity Cost and Personal Activity Using Spark Framework---使用Spark框架的基于机会成本以及个人活动群组推荐机制

    来源EDB2018---EDB 一.摘要: 组推荐是将一种项目(例如产品.服务)推荐给由多个成员组成的组的方法. 最小痛苦法(least Misery)是一种具有代表性的群体推荐方法,其能够推荐考虑群 ...

  10. php数组 匹配键值

    1.array_search() //判断键值是否在数组中,//存在,返回值对应的键;//不存在,返回false;//例子:$type = array( "选考" => 'o ...