Days 1 to 12 of the “100 Days of Swift” course make up the “Introduction to Swift” section.
Day 8‘s lesson covered structs, properties, and methods. The specific sections were: creating your own structs, computed properties, property observers, methods, mutating methods, properties and methods of strings, and properties and methods of arrays.
Thoughts about Day 8
I’ve used structs in the past when coding in Java and C for personal projects. What I like about structs in Swift is that the code syntax is less verbose than in Java and C. I especially like the property observers (didSet and willSet) keyword functionality available in Swift’s struct.
My Day 8 notes taken from my paper notebook:
- Creating your own structs
- Swift’s struct formatting similar yet simpler than struct in Java and C.
- the struct lesson preparing us for object-oriented class types.
- Computed properties
- constants cannot be computed properties.
- Property observers
- property observers let you run code before or after changes are made to the associated property’s value.
- didSet = property observer that executes its code block AFTER its associated property’s value changes.
- willSet = property observer that executes its code block BEFORE its associated property’s value changes. Commonly used when you need to know the state of your program/app before a change is made.
- property observers CANNOT be attached to a constant.
- Methods
- methods can refer to the other properties and methods inside their type.
- methods avoid namespace pollution, meaning the method’s unique name won’t cause conflicts with other methods that have identical names because the method’s scope is contained within its parent struct.
- namespace is structName.methodName, which means that a method named getStatus() can be used in a struct named power and another struct named light without worry of both getStatus() methods conflicting with each other. Reason is because power.getStatus() and light.getStatus() are unique.
- Mutating methods
- you can only modify the properties of a struct ONLY if the struct is declared using var, not using let.
- a method that was NOT declared using the keyword mutating CANNOT call a method that was declared using keyword mutating.
- remember that method names must start with keyword func and that the method name must be followed by parenthesis ().
- Properties and methods of strings
- in Swift, strings are structs that provide lots of functionality.
- Properties and methods of arrays
- arrays are also structs. They have their own properties and methods that can be used to manipulate the array.
- remember that you CANNOT append or remove or modify in any way the contents of an array declared as constant.
Today’s total study time: 2 hours 45 minutes
100 Days of Swift cumulative study time: 21 hours 45 minutes