Classes, Structures and Enumerations
Similarities
They all have very similar declaration syntax. They only difference is a class can specify a super class.
class ViewController: ... { ... }
struct Client { ... }
enum Operation { ... }
They all can declare properties and functions. The difference to note is that there can't be any stored properties on an enum. Enums keep any stored data in associated values much like optionals, but it is possible to have computed properties on them.
func doit(argx argi: Type) -> ReturnValue { ... }
var storedProperty = <initial value> (not enum)
var computedProperty: Type {
get { ... }
set { ... }
}
They can all have initializers except enums (which don't need them because you can just declare the case you want).
init(arg1x arg1i, arg2x arg2x: Type, ...) { ... }
Differences
Value type vs. Reference type
Structs and Enums are value types, they get passed around by making copies of themselves
- Copied when passed as an argument to a function
- Copied when assigned to a different variable
- Immutable if assigned to a variable with let
- when assigned to a let variable no matter how complex the struct or enum you can't call any of if mutating functions
- function parameters are let
- You must note any func that can mutate a struct or enum with the keyword
mutating
Classes are reference types, which pass around a reference to where they live in memory (in the heap).
- references are counted and collected automatically
- Constant pointers to a class (let) still can mutate by calling methods and changing properties
- Even when passed as an argument a copy does not get made. (Just passing a pointer to the same instance)
Inheritance is unique to classes.