swift语言点评十-Value and Reference Types
结论: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的更多相关文章
- swift语言点评十九-类型转化与检查
1.oc比较: -(BOOL) isKindOfClass: classObj判断是否是这个类或者这个类的子类的实例 -(BOOL) isMemberOfClass: classObj 判断是否是这个 ...
- swift语言点评十八-异常与错误
1.错误类型与枚举的结合 enum VendingMachineError: Error { case invalidSelection case insufficientFunds(coinsNee ...
- swift语言点评十六-Initialization && Deinitialization
initial value:必须初始化.不影响观察者 Classes and structures must set all of their stored properties to an appr ...
- swift语言点评十四-继承
Overriding A subclass can provide its own custom implementation of an instance method, type method, ...
- swift语言点评十五-$0
import UIKitimport XCPlayground class ViewController: UIViewController { func action() { print(" ...
- swift语言点评十二-Subscripts
Classes, structures, and enumerations can define subscripts, which are shortcuts for accessing the m ...
- Swift语言指南(十)--字符串与字符
原文:Swift语言指南(十)--字符串与字符 字符串是一段字符的有序集合,如"hellow,world"或"信天翁".Swift 中的字符串由 String ...
- swift语言点评四-Closure
总结:整个Closure的作用在于简化语言表述形式. 一.闭包的简化 Closure expression syntax has the following general form: { () -& ...
- swift语言点评二十-扩展
结论:扩展无法修改原来的数据结构. Extensions can add new functionality to a type, but they cannot override existing ...
随机推荐
- 关于Java中equal函数和==的一些区别
equal函数比较的到底是什么,很明显是比较的值,但是什么值?与==比较的堆中的内存地址不同,其比较的是对象的值,包括各个属性的值.我们在重新overriding此方法时首先要判断是否为同一对象,如果 ...
- android 给imageView,文字等加上阴影[记录]
1.链接 https://github.com/Devlight/ShadowLayout 2.效果 3.code compile 'com.github.devlight.shadowlayout: ...
- Linux crontab 定时任务设置
第1列分钟1-59第2列小时1-23(0表示子夜)第3列日1-31第4列月1-12第5列星期0-6(0表示星期天)第6列要运行的命令 下面是crontab的格式:分 时 日 月 星期 要运行的命令 这 ...
- cache(缓存)的作用
cache的作用: 连接文件.内存与应用,为信息流在三者之间流动提供通道: 存储管理:对外与对内: 存取效率: 多线程: 一次存储:分批存储? 系统的缓存控制机制(虚拟内存)使用分段分页与命中机制. ...
- JS怎样写闰年
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 发个ZKW线段树板子测试一下代码高亮
是我,Long time no see --Jim 先安利 Wolves 歌手:Madilyn Bailey http://music.163.com/song/524149464 ...
- BZOJ 5020 [THUWC2017]Drown in the math ocean (LCT+求导)
题目大意: 太长了略 洛谷题面传送门 嗯,数学题 感觉考试要是出这种题我就死翘翘了[逃 不用想都知道要$LCT$维护断边连边,但询问该如何处理呢 利用题目给出的公式 $f(x)=\sum_{i=0}^ ...
- 光盘文件的挂载和yum源配置
一.挂载光盘文件 1.将光盘推入 2.新建挂载点 mkdir /mnt/cdrom 3.挂载 3.1临时挂载 mount /dev/dcrom /mnt/cdrom 或者 mount –t iso ...
- 紫书 例题8-1 UVa 120(构造法)
#include<cstdio> #include<iostream> #include<sstream> #include<algorithm> #d ...
- spring boot pom
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...