Value and Reference Types

Types in Swift fall into one of two categories:

1) “Value Types” -> where Each instance keeps a unique copy of its data. Usually defined by

  • structs (incl. arrays and dictionaries)
  • enumerations
  • tuple
  • basic data types (boolean, integer, float, etc.)

2) “Reference Types” -> where Instances share a single copy of the data, and the type is usually defined as a class.

Now we will explore the merits of value and reference types, and how to choose between them.

What’s the Difference?

Value Type  -> 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 = 42				// Changes a, not b
println("\(, \(")	// prints "42, -1" 
Reference Type -> 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 = 42		// changes the instance referred to by x (and y)
println("\(, \(")	// prints "42, 42"

So 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

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s