Interview Questions: What is the difference between struct and class in Swift? When you'd use one or another?

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.

Structs and classes in Swift are very similar and different at the same time. This is a fundamental language question commonly asked on iOS interviews to gauge your level of understanding of Swift and the features it offers.

Expected answer:

Structures and Classes are very similar in Swift. Both can have properties, methods, subscripts, initializers, be extended/have a super type, conform to protocols.

Classes are reference types, they increase their reference count when passed to a function or assigned to a variable or constant. They also have some extra stuff like inheritance from a superclass, type casting, and deinitializers (former dealloc).

Structs are so called value types. That means that when a struct is assigned to a variable or constant or passed to a function its value is copied instead of increasing its reference count.

The key thing choosing between using a class or a struct is reference or value passing. If you need to store some primitives (i.e. Ints, Floats, Strings, etc.) then use struct if you need custom behavior where passing by reference is preferable (so that you refer to the same instance everywhere) then use class.

Red flag:

A red flag for this kind of question would be saying that you don't really use structs and prefer classes everywhere, just look in good old Objective-C. Structures is a great modern addition to Swift language that yet again, just like strong typing, let/var, and Optionals, forces developers to think harder about the data they use in their apps.

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