Skip to content

Instantly share code, notes, and snippets.

@koher
Created June 5, 2020 13:54
Show Gist options
  • Save koher/8d7b2b76f6dba2a5e5c940e1b77023fa to your computer and use it in GitHub Desktop.
Save koher/8d7b2b76f6dba2a5e5c940e1b77023fa to your computer and use it in GitHub Desktop.
// `Foo` is an immutable class
final class Foo {
let value: Int
init(_ value: Int) {
self.value = value
}
}
// Adds `mutating func` to `Foo`
protocol Incremental {
init(_ value: Int)
var value: Int { get }
mutating func increment()
}
extension Incremental {
mutating func increment() {
self = Self(value + 1)
}
}
extension Foo: Incremental {}
// `Foo` is immutable but it can be changed
var foo: Foo = Foo(2)
foo.increment()
print(foo.value) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment