Using Value and Reference Types Together

This chapter may have made you wonder, Can I put a value type inside of a reference type? Can I put a reference type inside of a value type? The answer to both of these questions is Yes, and you did the latter by adding a property of the class GreekGod to Pantheon. But you must be very careful about using a reference type inside of a value type. Consider the following example that changes the name of hecate.

Listing 18.12  The Romans are coming

...
struct Pantheon {
    var chiefGod: GreekGod
}

let pantheon = Pantheon(chiefGod: hecate)
let zeus = GreekGod(name: "Zeus")
zeus.name = "Zeus Jr."
zeus.name

pantheon.chiefGod.name // "AnotherHecate"
let greekPantheon = pantheon
hecate.name = "Trivia" ...

Get Swift Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.