Interview Questions: What is let and var in Swift?

Update: I'm working on a book that helps you ace iOS interviews. Sign up to the waitlist here: http://iosinterviewguide.com/

In this series of blog posts I talk about commonly asked tech iOS interview questions.

This is a basic Swift question that might open up opportunities for deeper discussions around language semantics and mutability/immutability in languages in general and their respective advantages and disadvantages. Be ready to go either direction.

Expected answer:

let keyword is used to declare a constant and var keyword is used to declare a variable. Variables created with both of them are either references/pointers or values. The difference between them is that when you create a constant with let you have to give it a value upon declaration (or within the calling scope)1 and you 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 (i.e. be nil).

This is a fundamental Swift thing that you should be familiar with. Unlike with Objective-C where everything is dynamic and can be nil and nil in turn can receive messages without breaking everything in Swift you have to be very explicit about what you are declaring.

At the end of the day let, var, nil, and Optionals help define how you handle state in your apps. Swift forces you to be more explicit about it.

Update: I'm working on a book that helps you ace iOS interviews. Sign up to the waitlist here: http://iosinterviewguide.com/

comments powered by Disqus