Codementor Events

Swift — Reference Type vs Value Type

Published Aug 17, 2018

On Swift, Refer to the Apple Document ClassesAndStructures: Class will be known as Reference Type and Struct will be Value Type:

  • Classes Are Reference Types: Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead.

  • Structures and Enumerations Are Value Types: A value type is a type whose value is copied when it is assigned to a variable or constant, or when it is passed to a function.

So let’s try the example below to understand what are Reference Type, Value Type:

class HumanClass { var name: String init(name: String) { self.name = name } } var classyHuman = HumanClass(name: "Bob") classyHuman.name // "Bob" var newClassyHuman = classyHuman // Created a "copied" object new ClassyHuman.name = "Bobby" classyHuman.name // "Bobby"

When I changed the name property of newClassHuman to “Bobby” the name property of the original object, classyHuman also changed to “Bobby”.

So how about Struct, let’s see the example below:

struct HumanStruct { var name: String } var humanStruct = HumanStruct(name: "Bob" ) var newHumanStruct = humanStruct // Copy and paste newHumanStruct.name = "Bobby" humanStruct.name // "Bob"

As the example above I did the same thing with Class example but got the different result.

So In Classes, when you make a copy of a variable, both variable referring to the same place in memory. A change to one of the variables will change the other that be called Reference Type. In Struct when you copy and paste variables it will be created the new place in memory so when you change one the other won’t be changed that be call Value Type.

Discover and read more posts from Anh Tran
get started
post commentsBe the first to share your opinion
Show more replies