I want to check if I have a corect understanding of Swift memory: Is it true that by encapsulating the changeable (aka var tagIDs ) inside it's own Metadata struct, now, when tagIDs changes, it won't re-create a new Book only new Metadata ?:
struct Book {
var metadata: Metadata
let title: String
let localURL: URL
struct Metadata {
fileprivate var tagIDs: Set<UUID> = []
mutating func addTag(_ tagID: UUID) {
tagIDs.insert(tagID)
}
mutating func removeTag(_ tagID: UUID) {
tagIDs.remove(tagID)
}
func hasTag(_ tagID: UUID) -> Bool {
tagIDs.contains(tagID)
}
}
}
I'm not entirely sure what you mean by that, but I don't see how you can change the metadata property without creating a new Book, since you've made all of the book's properties immutable.
My question is, when a struct's mutating function is called, CoW kicks in and creates a new struct behind the scenes, right?
Is there any sort of benefit in having the Metadata sub-struct (so to speak)? Or does it not make a difference at all? (having mutating properties wrapped in another struct)
I was thinking that somehow, this way (with the Metadata struct) there's only a new Metadata that gets created, and not a entire new Book, in a scenario like:
let url = URL(string: "https://swifteducation.github.io/assets/pdfs/XcodeKeyboardShortcuts.pdf")!
var book = Book(title: "Book title", localURL: url)
book.metadata.addTag(UUID())
Ah, no. Mutating part of your struct only mutates that part of your struct. Copy-on-write is not a built in compiler optimization, it's something you have to design into your types yourself. All of the standard library collection types that manage allocated memory implement CoW, but your struct doesn't.
If someone else has a copy of your metadata set, then it will trigger copy-on-write if you change that metadata set, but that will happen regardless of whether it's wrapped in its own struct. Changing a field of a struct only causes CoW to kick in if the author of that struct implemented copy-on-write.
Neither version of Book would cause you to recreate that book just because you updated the metadata.