2

If I force unwrap an optional instance of a struct, does Swift make a copy of it?

For example, in the following code, where Point is a struct, does Swift copy (internally) point when I unwrap it?

var point: Point?
point = Point(x: 0, y: 0)
print(point!.x)

Follow-Up Question

If not, then would

if point != nil {
  print(point!.x)
}

be more efficient than

if let point = point {
  print(point.x)
}

since I assume the latter code (due to the assignment) causes Swift to make a copy of point, correct??

mfaani
  • 33,269
  • 19
  • 164
  • 293
ma11hew28
  • 121,420
  • 116
  • 450
  • 651

1 Answers1

1

Good question.

If I force unwrap an optional instance of a struct, does Swift make a copy of it?

Not yet.

print(point!.x)

Actually means:

switch point {
    case .some(let _point): print(_point.x) 
    case .none: fatalError()
} 

But Swift's architecture is copy on write. So so far there is no change, hence no copying happening

However if you do something like:

if var point = point { // notice the usage of `var` instead of `let`
    point.x = 5 // copy on write happened at this line. Because you just changed a property of `point` — assuming that `x` is a value type
}
mfaani
  • 33,269
  • 19
  • 164
  • 293
  • 1
    Swift does **not** use a strictly copy on write behavior for arbitrary structs. Read more at https://stackoverflow.com/questions/43486408/does-swift-copy-on-write-for-all-structs – jtbandes Mar 25 '20 at 23:38
  • @jtbandes woah. I didn't know of that. And not something I fully understand. Hence any reader should read my answer with CAUTION – mfaani Mar 26 '20 at 00:13