Skip to content

Instantly share code, notes, and snippets.

@mbrandonw
Created July 8, 2020 12:05
Show Gist options
  • Save mbrandonw/94d941a5b2a113dd098de1ed9ffabe48 to your computer and use it in GitHub Desktop.
Save mbrandonw/94d941a5b2a113dd098de1ed9ffabe48 to your computer and use it in GitHub Desktop.

FB7867609

Consider the following code:

class ViewModel: ObservableObject {
  @Published private(set) var value = 0
}

let vm = ViewModel()

// vm.value = 42 // <- This fails since value is private

Just(42).assign(to: vm.$value) // this compiles

print(vm.value) // and changes the private value

It is unexpected that you can use the assign(to:) method on publisher to circumvent access modifiers on a class, allowing you to change private fields.

I understand why this is possible (due to how property wrappers work), but it is incredibly subtle and gives an escape hatch to break encapsulation of the class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment