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, let
and var
behave differently with structs and classes.
Mutability
Using 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.
The struct milo
was created with let
therefore it cannot have its variables changed. The dog cannot be renamed.
The struct 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 let
and var
is the ability to reassign the variable to a different class of the same type. The let
and var
keywords do not affect the ability to change a variable on a class.
The above example shows the difference between let
and 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 var
.
Mutating Functions
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 var
.
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.
Final Thoughts
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 String
, Array
, Dictionary
, Int
, Float
, 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 NSArray
and NSMutableArray
.
Carlos Paelinck
Related Posts
-
Writing a Cordova Plugin in Swift 3 for iOS
This blog post is an update to one I wrote back in April 2016 and…
-
Writing a Cordova Plugin in Swift 3 for iOS
This blog post is an update to one I wrote back in April 2016 and…