SoFunction
Updated on 2025-04-06

The difference and use of value types and reference types in Swift

There are two types in Swift:

●Value Types: Each instance retains a unique copy of the data, generally in the form of a struct, an enum, or a tuple.
●Reference Type: Each instance shares the same data source, generally in the form of a class.

In this blog post, we will introduce the advantages of the two types and how to choose to use them.

The difference between value type and reference type

The most basic results of value types and reference types are respectively copied. When a value type is copied, it is equivalent to creating a completely independent instance. This instance retains its own unique data, and the data will not be affected by data changes in other instances:

Copy the codeThe code is as follows:

// Here is an example of value type
    struct S { var data: Int = -1 }
    var a = S()
var b = a
= 42                                                             �
println("\(), \()")     // Output result "42, -1"

The value type is like a copy of the ID card. After copying it, modify the content on the original, and the content on the copy will not change.

On the other hand, when copying a reference type, it is actually silently creating a shared instance clone, and the two share a set of data. Therefore, modifying the data of any of the instances will also affect the other one.

Copy the codeThe code is as follows:

// Here is an example of a reference type
    class C { var data: Int = -1 }
    var x = C()
var y = x                                                            �
= 42                                                             �
println("\(), \()")     // Output result "42, 42"

Mutation (modify) role in security

Value types are more likely to be cleared in a lot of code than reference types. If you always get an independent copy of the instance, you can rest assured that it will not be silently modified by other parts of your app's code. This is particularly important in a multi-threaded environment, because another thread may modify your data secretly. Therefore, serious program errors may be caused, which are very difficult to eliminate during debugging.

Since the difference mainly lies in the consequences of modifying the data, when the data of the instance is read-only and does not require changes, there is no difference between which type to use.

You may be thinking, sometimes I may also need a completely unchanging class. This makes it easier to use Cocoa NSObject objects, and can retain the benefits of value semantics. Today, you can write an immutable class in Swift by using only immutable storage properties and avoiding any API that can modify state. In fact, many basic Cocoa classes, such as NSURL, are designed as immutable classes. However, the Swift language currently only forces immutability of value types such as struct and enum, but does not use reference types such as class. (For example, it is not supported to force restriction of subclasses to immutable classes)

How to choose a type?

So when we want to create a new type, how do we decide whether to use value type or reference type? When you use the Cocoa framework, many APIs need to be used through subclasses of NSObject, so you must use the reference type class. In other cases, there are several guidelines:

When should I use value type:

●When using the == operator to compare the data of the instance
●When you want the copy of that instance to remain independent
●When data will be used by multiple threads

When should I use the reference type (class):

●When using the == operator to compare instance identities
●You want to create a shared, mutable object

In Swift, arrays (Array), strings (String), and dictionary (Dictionary) are all value types. They are just like simple int values ​​in C language, they are independent data individuals. You don't need to spend any effort to prevent other codes from modifying them secretly. More importantly, you can pass variables safely between threads without having to synchronize them specifically. In the spirit of Swift's high security, this mode will help you write more controllable code using Swift.