Created
May 15, 2020 07:48
-
-
Save 4np/e3d6f1a43a528f0f9d9c94d7af539aa2 to your computer and use it in GitHub Desktop.
Swift value type memory management
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
func address(of object: UnsafeRawPointer) -> String { | |
let addr = Int(bitPattern: object) | |
return String(format: "%p", addr) | |
} | |
struct Foo { | |
public var baz: String | |
} | |
struct Bar { | |
public private(set) var baz: String | |
mutating func updateBaz(with text: String) { | |
baz = text | |
} | |
} | |
var foo = Foo(baz: "yankee") | |
print("Foo holds \(foo.baz)", address(of: &foo)) | |
foo.baz = "doodle" | |
print("Foo holds \(foo.baz)", address(of: &foo)) | |
var bar = Bar(baz: "sporty") | |
print("Bar holds \(bar.baz)", address(of: &bar)) | |
bar.updateBaz(with: "spice") | |
print("Bar holds \(bar.baz)", address(of: &bar)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Playground demonstrates that a setter is implicitly mutating. You will not get a copy of a struct (value type - copy on write) when you directly update one of its properties (
Foo
). There is no need for amutating
method to do so (Bar
). When you run, the output will be something like:Both
Foo
as well asBar
have the same address space after mutation.