Update: I've published a book that helps you prep and ace iOS interviews: 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, 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 (unlike structs), 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've published a book that helps you prep and ace iOS interviews: http://iosinterviewguide.com/