What is the core difference separating these two types? Reference types share an individual copy of their data while value types retain a unique copy of their data.
分离这两种类型的核心区别是什么? 引用类型共享其数据的单个副本,而值类型保留其数据的唯一副本。
(Reference Types)
Classes define a reference type, which is similar to Objective-C. They consist of shared instances that can be passed around and referenced by many variables. Have a look at this code:
类定义了引用类型,类似于Objective-C。 它们由共享实例组成,这些实例可以传递并由许多变量引用。 看一下这段代码:
// Reference Types:class Person {
var isHappy = true
}let michael = Person()
let john = michaeljohn.isHappy = falsemichael.isHappy // false
john.isHappy // false
Changing one instance changes the other since they both reference the very same object. They both point to the identical location in memory. Still don’t get it? Maybe this video will help:
更改一个实例会更改另一个实例,因为它们都引用了相同的对象。 它们都指向内存中的相同位置。(Value Types)
Let’s look at some code first:
让我们先来看一些代码:
// Value Types:var a = 2
var b = a
b += 2a // 2
b // 4
and
和
struct Person {
var isHappy = true
}var michael = Person()
var john = michael
john.isHappy = falsemichael.isHappy // true
john.isHappy // false
Now you should be able to know the contrast between the two types. If not hereabouts is a video that explains value types:
现在,您应该能够知道两种类型之间的对比。 如果没有关于视频的内容,那么它会解释值的类型:
(Mutability)
For reference types as you could have noticed, we use constants with the let keyword. You can’t change the instance of the constant references, but you can mutate the instance itself. On the other hand for value types, let means the instance must remain constant. No properties of the instance will ever change, despite whether the property is declared with let or var.
您可能已经注意到,对于引用类型,我们在let关键字中使用常量。 您不能更改常量引用的实例,但可以对实例本身进行突变。 另一方面,对于值类型, let表示实例必须保持不变。 不管该属性是用let还是var声明的,实例的任何属性都不会改变。
(When to Use Reference Type)
- Use a reference type when comparing instance identity with === makes sense
在将实例标识与===进行比较时,请使用引用类型 - Use a reference type when you want to create a shared, mutable state
要创建共享的可变状态时,请使用引用类型
(When to Use Value Type)
- Use a value type when comparing instance data with == makes sense
在将实例数据与==进行比较时,请使用值类型 - Use a value type when copies should have independent state
当副本应具有独立状态时,请使用值类型 - Use a value type when the code will use this data across multiple threads
当代码将在多个线程中使用此数据时,请使用值类型
(Conclusion)
These are the basics that you should know. I myself watched all the videos that I linked on this post and they explained quite a lot about how Swift and SwiftUI work. You will get a better understanding of how to model your data in your app. What value types should you use and when? If you want to go deeper on the topic of property wrappers which will put this knowledge into SwiftUI practice watch this video:
这些是您应该知道的基本知识。 我本人观看了我在这篇文章上链接的所有视频,并且他们对Swift和SwiftUI的工作方式进行了很多解释。 您将更好地了解如何在应用程序中对数据建模。 您应该使用什么值类型?何时使用? 如果您想深入了解属性包装器这一主题,它将把这些知识带入SwiftUI实践中
翻译自: https://medium.com/macoclock/reference-vs-value-types-in-swift-c1ece75b8a55