Classes and Structs in Swift
The differences between let and var, class and struct.
With the introduction of Swift, native iOS development has become more approachable and modern. Classes and structs in Swift are basic constructs of your program. In Swift, both classes and structs can have properties and functions. The key difference is structs are value types and classes are reference types. Because of this,
var behave differently with structs and classes.
let on a struct makes that object a constant. It cannot be changed or reassigned and neither can its variables. A struct created as a
var can have its variables changed.
milo was created with
let therefore it cannot have its variables changed. The dog cannot be renamed.
meg was created as a variable, therefore we can change its variables and rename the dog.
Since classes are reference objects the only difference between
var is the ability to reassign the variable to a different class of the same type. The
var keywords do not affect the ability to change a variable on a class.
The above example shows the difference between
var with classes. Julia cannot upgrade her car since it’s immutable (let). She can however correct the model of the car she actually purchased. Shelli can upgrade to the R8 because her car is a
Functions marked as mutating change internal property values. Mutating functions are only present on structs and can only be used on structs created as a
The apple cannot be eaten since it’s immutable (let) unlike the orange which can be eaten because it’s a variable.
Modifying structs in external functions
Since structs are value types, they are pass by value. This means their contents will be copied when passed into functions. A struct variable can be marked as an inout parameter if it needs to be modified inside a function and its value persisted outside of the scope of the function.
In Swift structs and classes give you both value and reference-based constructs for your objects. Structs are preferred for objects designed for data storage like
Array. Structs also help remove memory issues when passing objects in a multithreaded environment. Classes, unlike structs, support inheritance and are used more for containing logic like
UIViewController. Most standard library data objects in Swift, like
Boolean, are all structs, therefore value objects. The mutability of
var versus let is why in Swift there are no mutable and non-mutable versions of collections like Objective C’s