Does guard make a copy of variables in swift

Viewed 828

In swift you can unwrap optional values with a guard statement

guard let foo = foo else { return nil }

Is this statement making a copy of foo? In other words, could this statement be potentially expensive if foo is very large?

4 Answers

Actually this depends on type of foo e.x class type won't create a copy unlike struct type

guard isn't a magic keyword it simply if not presented in 1 word

 guard let foo = foo else { return nil }

Could this statement be potentially expensive if foo is very large?

Instead of asking yourself the question that way, ask it this way: what if you had said

if foo != nil {
    let foo = foo!
    // everything else here
}

Was saying foo! to unwrap the Optional "expensive"? Whatever your answer is, it must be exactly the same for guard let foo = foo, because they both do exactly the same thing: they test for nil and, if safe, they unwrap the Optional. And that is all they both do. The one is merely syntactic sugar for the other.

You have two ways:

1- To only check if this foo does not equal nil
In this case you can check if foo is nil or not

if foo != nil {
    // do you work here
}

2- To get information from foo
In this case, you have to unwrap this optional (with guard-let or if-let statements) and here we have two cases:
- if foo is a class, then it’s a reference type. so there will be no copy and a reference to this instance is created
- if foo is a struct, then it’s a value type. so an entirely new instance is created (copied from the original)
Also you can read this answer to see should you choose struct or class in swift

If the property you're unwrapping is a reference type (e.g. a class) then no it will not make a copy, it will just create a new property with a reference to the original instance.

If the property you're unwrapping is a value type (e.g. struct) then it will make a copy.

Related