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??
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.