@morpheus is asking great questions on Day 12:
Why is this?
And why is this not an option instead of adding a complicated function to create a separate copy?
I took a step back to see what @twoStraws is trying to convey.
How to not have a class reference the same data in a copy seems like an odd lesson.
To reiterate, consider a cardboard box. Write MORPHEUS
on a piece of paper and put it in the box.
Now, point to the box. If someone wants to know what you're pointing to, you can say you are REFERRING to a box with some data in it.
Now ask your BFF to point to the same box. What is she referring to?
You both are referencing the same box, including the single piece of paper (the data) on the inside. Here's some code to illustrate. Copy this to Playgrounds and run!
// Copy and run in Playgrounds
class CardboardBox {
var id = UUID() // Get a unique id when created
var pieceOfPaper = "blank paper" // Write something on the paper
func changePieceOfPaper(to newString: String) {
pieceOfPaper = newString // overwrite with new data
}
}
struct Person {
let name: String // person gets a name
let pointsToBox: CardboardBox // person points to a box
var nameInTheBox: String { // Let's see what's in the box!
"Box ID: \(pointsToBox.id) contains paper with name \(pointsToBox.pieceOfPaper) "
}
}
// Create a box
let someBox = CardboardBox()
// Write a name on the paper in the box
someBox.changePieceOfPaper(to: "twoStraws")
// Create two people
let morpheus = Person(name: "Morpheus", pointsToBox: someBox)
let bff = Person(name: "Taylor Swift", pointsToBox: someBox) // bff points to same box!
// Are they the same?
print(morpheus.nameInTheBox) // both of you are pointing to the same box with the same data
print(bff.nameInTheBox) // verify this is the same
assert(morpheus.pointsToBox.pieceOfPaper == bff.pointsToBox.pieceOfPaper)
// Now someone asks your bff to change the name on the pieceOfPaper
bff.pointsToBox.changePieceOfPaper(to: "Obelix")
// Are they the same?
print(morpheus.nameInTheBox) // both of you are pointing to the same box with the same data
print(bff.nameInTheBox) // verify this is the same
assert(morpheus.pointsToBox.pieceOfPaper == bff.pointsToBox.pieceOfPaper)