Avoiding unbreakable reference cycle with value types and closures?

Part of the reason there's no mutability checking for classes is because it's (1) hard for the programmer to get right, and (2) doesn't provide any safety or optimization guarantees anyway. This is well-explored in C++, where having a const State & means that you can't mutate the state, but it doesn't mean that someone else can't mutate the state while you're using it. ObjC/Foundation's NSFoo/NSMutableFoo pattern is roughly equivalent to that, with an added culture (and a little bit of language sugar) around eagerly copying values so they don't change out from under you.

A truly immutable class has value semantics, but that's harder to get set up correctly in the first place. You'd really want some kind of "freeze" operation that says "okay, I'm done setting this up so now it's okay to share it", and a possible "unfreeze" for "okay, I know I have unique ownership; let me modify this again".

But rather than adding these mechanisms directly to classes, it might be more interesting to explore making Swift's efficient-copy-on-write patterns easier to adopt. (The same mechanisms allow for error-on-shared-write, although without the compile-time enforcement.)

8 Likes