Use struct to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.

As per the apple documentation String is a Struct (value type) and NSString is Class (Reference type). Reference type means if we change the value of reference it will reflect in the original value too. check the below code.

Reference Types vs. Value Types

So, what’s the core difference between these two types? The quick and dirty explanation is that reference types share a single copy of their data while value types keep a unique copy of their data.

Swift represents a reference type as a class. This is similar to Objective-C, where everything that inherits from NSObject is stored as a reference type.

There are many kinds of value types in Swift, such as struct, enum, and tuples. You might not realize that Objective-C also uses value types in number literals like NSInteger or even C structures like CGPoint.

To better understand the difference between the two, it’s best to start out with what you may recognize from Objective-C: reference types.

https://docs.swift.org/swift-book/ReferenceManual/Attributes.html

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:

// Value type example

struct S { var data: Int = -1 }

var a = S()

var b = a // a is copied to b

a.data = 42 // Changes a, not b

println("\(a.data), \(b.data)") // prints "42, -1"

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.:

// Reference type example

class C { var data: Int = -1 }

var x = C()

var y = x // x is copied to y

x.data = 42 // changes the instance referred to by x (and y)

println("\(x.data), \(y.data)") // prints "42, 42"

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内存管理:值类型与引用类型的更多相关文章

  1. Swift 中的值类型与引用类型

    顶级修饰 次级修饰 赋值类型 存储类型 值类型 值类型   深拷贝 栈 值类型 引用类型 浅拷贝 堆 引用类型 值类型 浅拷贝 堆 引用类型 引用类型 浅拷贝 堆 复合引用类型会改变内部值类型的存储行 ...

  2. swift的值类型和引用类型

    前言 最近在学设计模式中,发现 Swift 中的 struct,class 以及 enum 在一般的使用中能够做到互相替换,因此探究其背后的逻辑就十分有必要.而这一问题又引出了 Swift 中的值类型 ...

  3. .NET面试题解析(01)-值类型与引用类型

      系列文章目录地址: .NET面试题解析(00)-开篇来谈谈面试 & 系列文章索引 常见面试题目: 1. 值类型和引用类型的区别? 2. 结构和类的区别? 3. delegate是引用类型还 ...

  4. .NET基础知识(01)-值类型与引用类型

    常见面试题目: 1. 值类型和引用类型的区别? 2. 结构和类的区别? 3. delegate是引用类型还是值类型?enum.int[]和string呢? 4. 堆和栈的区别? 5. 什么情况下会在堆 ...

  5. c# 值类型与引用类型的传参(形参与实参)

    形参是指被调用方法中的参数 实参是指传递给方法的参数 (1)值类型传参是按值传递 值类型传参,形参接受到的是实参的一个副本,即形参发生变化,实参不会发生任何变化 (2)引用类型参数按值传递 当参数传递 ...

  6. CLR值类型和引用类型

    知识点:引用类型.值类型.装箱.拆箱 CLR支持两种类型:引用类型和值类型.引用类型在堆上分配内存,值类型在线程栈上分配内存.值类型与引用类型如下所示: 值类型对象有两种表示形式:未装箱和已装箱.将一 ...

  7. Swift 值类型/引用类型

    1.值类型/引用类型 在 Swift 语言中,所有的类型都可以被分为 "值类型" 或者 "引用类型",可以将其理解为函数参数传递的方式. 值类型表示的是将它传递 ...

  8. Swift - 值类型与引用类型的初步探究

    前言 swift中的结构体和类在组成和功能上具有一定的相似性.两者都可以含有成员属性.成员方法用于数据存储和功能性模块封装.往往造成不知如何对二者进行区分和使用 值类型概念和引用类型概念 值类型的概念 ...

  9. Swift 值类型和引用类型

    Swift中的类型分为两类:一,值类型(value types),每个值类型的实例都拥有各自唯一的数据,通常它们是结构体,枚举或元组:二,引用类型(reference types),引用类型的实例共享 ...

  10. [你必须知道的.NET] 第八回:品味类型---值类型与引用类型(上)-内存有理

    原文地址:http://kb.cnblogs.com/page/42318/ 系列文章导航: [你必须知道的.NET] 开篇有益 [你必须知道的.NET] 第一回:恩怨情仇:is和as [你必须知道的 ...

随机推荐

  1. 新手之首次部署阿里云centos7+mysql+asp.net mvc core应用之需要注意的地方

    先来几个字,坑坑坑. 自己业余爱好者,签名一直捣鼓net+mssql,前阵买了阿里云esc,自己尝试做个博客,大体架子都打好了,本地安装了mysql,测试了也没问题. 部署到阿里云centos7,结果 ...

  2. 请比较throw 合throws的区别

    throw语句用在方法体内,表示抛出异常.throws语句用在方法声明的后面,表示再抛出异常,由该方法的调用者来处理.throws主要声明这个方法会抛出这种类型的异常,使它的调用者知道要捕获这个异常. ...

  3. c#如何禁用win7的任务管理器

    以前制作的桌面锁屏软件虽然也禁用过任务管理器,但是采取的是比较笨的方法,而且对操作系统还有一定的危害.因为任务管理也是一个窗体也就是说它中也是一个独立进程,所以只需要强制性关闭这个进程即可以关闭任务管 ...

  4. DOM增删改操作

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  5. pom.xml 如果使用 mvn exec:exec 命令运行项目

    pom.xml 如果使用 mvn exec:exec 命令运行项目,红色字体要与groupid相同 <project xmlns="http://maven.apache.org/PO ...

  6. c#实现内存映射文件共享内存

    原文:http://blog.csdn.net/wangtiewei/article/details/51112668 内存映射文件是利用虚拟内存把文件映射到进程的地址空间中去,在此之后进程操作文件, ...

  7. Flex Box 简单弹性布局

    弹性盒子模型有两种规范:早起的display:box 和后期的display:flex.它可以轻易的实现均分.浮动.居中等灵活布局,在移动端只考虑webkit内核时很实用. 一.display:box ...

  8. 【Python】Java程序员学习Python(七)— 文本类详解(字符串、str)

    如果一个女孩子喜欢看龙猫,那么请珍惜她,呵护她 任何一门语言,字符串总是最基本也是最需要掌握的一个变量,想想入门的Hello World,输出的就是字符串. 官方文档:https://docs.pyt ...

  9. HTML5-入门3。

    CSS选择器. 什么是标签选择器?作用: 根据指定的标签名称, 在当前界面中找到所有该名称的标签, 然后设置属性 格式: 标签名称{ 属性:属性值 } 标签选择器(html中的标签名称) id选择器( ...

  10. 解决国外模板h1、h2、h3...不显示中文文章标题的问题

    如果你经常用国外好看的网页模版时候,会遇到不显示中文文章标题的情况,显示英文标题却正常.遇到这个情况很多人认为应该修改CSS的font-family的字体,其实这是错误的,与CSS无关. 出现这种情况 ...