Skip to content

Instantly share code, notes, and snippets.

@Aenohe
Created December 27, 2017 19:35
Show Gist options
  • Save Aenohe/c8a11ce43bc1f8e388b5a132fde101f6 to your computer and use it in GitHub Desktop.
Save Aenohe/c8a11ce43bc1f8e388b5a132fde101f6 to your computer and use it in GitHub Desktop.
swift-mutability-tests
struct Test {
  var a: String
  var b: String
  var c: String
}

func copyTest(to: Test) -> Test {
  var copy = to
  
  withUnsafePointer(to: &copy) { print("\($0)") }
  
  //copy.b = "new world"
  
  withUnsafePointer(to: &copy.a) { print("string member a \($0)") }
  withUnsafePointer(to: &copy.b) { print("string member b \($0)") }
  withUnsafePointer(to: &copy.c) { print("string member c \($0)") }
  
  return copy
}

var test = Test(a: "hello", b: "world", c: "foo")

withUnsafePointer(to: &test) { print("\($0)") }

withUnsafePointer(to: &test.a) { print("string member a \($0)") }
withUnsafePointer(to: &test.b) { print("string member b \($0)") }
withUnsafePointer(to: &test.c) { print("string member c \($0)") }

test = copyTest(to: test)

withUnsafePointer(to: &test) { print("\($0)") }

withUnsafePointer(to: &test.a) { print("string member a \($0)") }
withUnsafePointer(to: &test.b) { print("string member b \($0)") }
withUnsafePointer(to: &test.c) { print("string member c \($0)") }

print(test.b)
var a = "hello"
var b = a

print(a)
withUnsafePointer(to: &a) { print("\($0)") }
print(b)
withUnsafePointer(to: &b) { print("\($0)") }

func mutate(value: inout String) {
  value = "mutated"
}

mutate(value: &a)

print(a)
withUnsafePointer(to: &a) { print("\($0)") }
print(b)
withUnsafePointer(to: &b) { print("\($0)") }


var c = "hello"

withUnsafePointer(to: &c) { print("c initial \($0)") }

func mutation(value: String) -> String {
  var value = value
  
  withUnsafePointer(to: &value) { print("c copy \($0)") }
  
  value = "mutated"
  
  return value
}

c = mutation(value: c)

print(c)
withUnsafePointer(to: &c) { print("c mutated \($0)") }

var a = 10
let ptr: UnsafeMutablePointer<Int> = &a

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