O'Reilly logo

Swift Programming: The Big Nerd Ranch Guide by John Gallagher, Matthew Mathias

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reference Semantics

Reference semantics work differently than value semantics. With value types, you get a copy of the instance when you assign it to a new constant or variable. The same is true when you pass an instance of a value type as the argument to a function. An instance of a reference type, however, behaves differently in that these two actions actually create an additional reference to the same underlying instance.

Let’s add a new class to model a Greek god to the playground to see just what this means.

Listing 18.3 Adding a Greek god class

import Cocoa

var str = "Hello, playground"
var playgroundGreeting = str
playgroundGreeting += "! How are you today?"
str

class GreekGod {
    var name: String
    init(name: String) {

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required