Immutability In Swift
Gustavo Barcena
JibJab Bros. Studios
"In functional programming, you think of immutable data structures and functions that convert them. In object-oriented programming, you think about objects that send messages to each other."
-Chris Eidhof [1]
Why use Immutability?
- Isolate variables that can change
- Prevent other actors from changing your data
- Immutable data is typically thread safe by default
let
Value and Reference Types
- We typically first learn these as pass by value and pass by reference
- Think about the difference in C between
- void functionA(int a)
- void functionA(int *a)
- Value types always create copy on assignment
- Reference types share data on assignment
"Use a value type when:
- Comparing instance data with == makes sense
- You want copies to have independent state
- The data will be used in code across multiple thread
Use a reference type (e.g. use a class) when:
- Comparing instance identity with === makes sense
- You want to create shared, mutable state" [2]
Value Types
Primitives
Tuples
Enumerations
Structs
Reference Types
Classes
Enums are powerful
- In a switch statement, Swift forces you to use all of possible values
- Enum are no longer just glorified ints.
- They can hold information as well
- Optionals are defined as an enum
- You can add functions, computed properties, initializers to enums
- Enums can conform to protocols
How NSString is similar
- NSString by itself is an immutable class
- However NSMutableString is a subclass of NSString
-
- polymorphisms allows use anywhere we use NSString
- (this is what copy is the recommended type for a string)
- Polymorphism can get in the way of immutablilty
- Swift doesn't support class immutability
What should I do?
Immutability as the default
- Prefer let instead of var everywhere
- Use structs before classes
- Use enums before structs
Questions?
Sources
- [1] http://www.objc.io/issue-16/power-of-swift.html
- [2] https://developer.apple.com/swift/blog/?id=10
- [3] http://nomothetis.svbtle.com/immutable-swift
Immutability In Swift
By Gustavo Barcena
Immutability In Swift
- 606