Hacking the iOS Interview

Swift — let vs var

Jayant Kumar Yadav
Hash Coding
Published in
3 min readFeb 15, 2021

--

Photo by Sebastian Herrmann on Unsplash

At first, it looks like a trivial question of Swift language. But this might lead to discussions around language semantics and its mutability/immutability in general. You have to be ready for this deep dive.

What are let and var ? What is the difference between them ?

Both let and var are for creating variables in Swift. let helps you create immutable variables (constants) while on the other hand var creates mutable variables. Variables created by both of them either hold a reference or a value.

The difference between them is that when you create a constant using let you have to assign something to it before the first use and can’t reassign it. And when you declare a variable with var it can either be assigned right away or at a later time or not at all and can be reassigned at any time.

Can we mutate function parameters ?

Function parameters are constants by default. Trying to change their value within functions body results in a compile-time error.

Line 2Cannot assign to value: ‘value’ is ‘let’ constant.

Have you ever wondered why function parameters are not variables? Find out here

Can you help compile this code? Explain the cause of compile-time errors, if any.

Structs have value type semantics in Swift. Whenever you try to mutate them, they get copied with mutation applied to them and reassigned back.

The let variables holding struct can’t mutate it as it would mean you are mutating value of the immutable variable which can not happen in Swift. On the other hand, the var variable holding struct can mutate itself. Similarly, the rule of let & var will apply to individual properties of the struct.

Line 7Cannot assign to property: ‘constantBlog’ is a ‘let’ constant.

Line 8 & 12Cannot assign to property: ‘claps’ is a ‘let’ constant.

Where do you think compile-time errors would be present in this code?

Classes have reference type semantics in Swift. Whenever you try to mutate them, the object stored elsewhere in memory gets mutated while the reference to it remains the same.

You can modify a class’s members whether or not the variable referencing it is mutable.

Line 13 & 17Cannot assign to property: ‘claps’ is a ‘let’ constant.

The whole point is that your interviewer wants to dig deep for your understandings of how mutation works in swift. What can be mutated and what not.

I hope you find this story helpful. If you liked it, share this with your community and feel free to give your claps below 👏 to help others find it! Thanks for reading.

Get notified every time we post a new story to our publication. Follow us now

We are dedicated to our goal to help every iOS developer grow and give their best in the interview. Every week we’ll be coming up with newer topics. Don’t miss them. Signup Now. ✉️

--

--