Reviewing closures, polymorphism, access control, static properties/methods
100 Days of SwiftUI — Day 15
I am getting ready for Bologna! I will leave tomorrow to get comfortable one day before as the workshop with Daniel Steinberg will start already at 9am, with registration from 8am!
So, let’s start with the review, which you can find here!
The first topic we are going to review today is properties. Properties are constants and variables that belong to a specific type, the same way as methods are functions belonging to a specific type. Practically speaking we will almost never use constants and variables outside of struct and classes so they will always (99.9%?!) be referred to as properties.
There are some nice quirks to properties, such as performing some actions before their value will be changed or just after that, using the so-called property observers. willSet { }
will execute the code inside the braces just before the value change, while didSet { }
will do so just after the value change. If we need to compare the old value and the new value we can use the automatically generated constants newValue
and oldValue
.
Computed properties allow us to generate the value of a property based on some other properties. If we need to perform something when the value is read we need to use get { }
while we need to use set { }
if we want to perform something when the value is written
. If we only need to do so when the value is read we can omit the get
entirely and just use return
.
Thesecond topic for today’s review are static properties and methods. Expanding from what we said before, we cannot access those properties from other parts of our program unless we decide to make them belong to the type itself instead of to instances of that type. To do that, we need to mark them as static
and to call them using TypeName.propertyName
.
The third topic covers access control. This allows us to define which part of the program should access our code. There are four different levels: public
, where everyone can read/write the property, internal
, where only our Swift code can do so (e.g.: if you ship a library, internal
code won’t be accessible to users/other developers), fileprivate
, which makes the property accessible only to Swift code in the same file where it was defined and, finally, private
, which makes the property available only to the type where it is defined or to its extensions.
I recall working on the Stanford course where we were required to specify access control for every single property… it was so confusing and the code became so heavy to read… I prefer not to write anything and then specify what is needed.
The fourth topic of review was polymorphism and typecasting. In short, as this was a very long video again, polymorphism describes the ability of a subclass to be, at the same time, itself and its superclass! The example you will find in today’s playground creates three classes, two of which inherit from the first one and add some functionality. Creating an array of three instances of those classes creates and array of objects of the first class’ type!
Typecasting, moreover, allows us to play with the subtle differences between types and try to convert one type into another, using as?
or as!
. As always, be careful with the exclamation mark because it will make your app crash.
The last review topic for today is closures. I expected a 25-minute long video and instead it was pretty short, probably because of all what was done previously. In short a closure is a variable that holds code, all the while capturing the environment where it is created. If the last parameter of a method is a closure we can use trailing syntax, which abbreviates the amount of code written, increasing its readability at the same time!
This concludes the review topics for today. Paul ended this article by attaching a crossword puzzle at the end. I will now print it and try to complete it! Here are my answers to the questions.
- Fixed-size collection of values of any type: TUPLE
- A custom type with cases and associated values: ENUMERATION
- Makes a method shared across all instances of a class or struct: ??? Static ??? -> yes, STATIC
- How we check for and extract the value inside an optional: ??? Unwrapping or Binding ??? I found UNWRAP, maybe it is correct.
- Type that stores data as pairs of keys and values: DICTIONARY
- Places variables into strings easily: INTERPOLATION
- Loop type commonly used to make infinite loops: WHILE
- A list of criteria that a type must conform to: PROTOCOL
- Evaluates multiple conditions in one block of code: ??? If-else statement ??? -> I found IF but I do not know if this counts as correct.
- Special method that creates instances of structs and classes: INITIALIZER
- Functions that accept one or more parameters of a specific type: VARIADIC
- Code to handle errors thrown by do: CATCH but I cannot find it -> Found it!
- Value passed into a function: PARAMETER (could also be ARGUMENT but…-> parameter was the good one.
- Unwrapping alternative to
if let
: GUARD - Sends back a value from a function: RETURN
- A catch-all case for switch blocs: DEFAULT
- An anonymous function that you can pass around as data: CLOSURE
- A whole number: INTEGER
- Telling Swift the specific type a variable should be: ANNOTATION
- Question marks after optionals: I don’t understand the definition, could be CHAINING? It seems not…-> maybe it is “Nil coalescing” but I cannot find neither NIL nor COALESCING … It was CHAINING in the end!
- Code that is triggered when properties change: OBSERVER
- May or may not exist: OPTIONAL
- Keyword that lets function parameters be modified outside the function: INOUT ma non lo trovo-> TROVATO!!!!!!!
- Access control that restricts a property to being used only inside its type: PRIVATE
- Skips the rest of the current loop iteration: CONTINUE
- Loop that always executes at least once: REPEAT
- The return type of a function that returns nothing: VOID
- How we refer to the current instance of an object: ??? -> SELF
- Struct initialiser that assigns values to all properties: MEMBERWISE
- The name for how values used in a closure are stored for later use: CAPTURING
- A variable attached to a struct or class: PROPERTY
- A type that spans values between two numbers: RANGE ??? I found it, but I didn’t know this was a type!
- Special syntax for final parameter closures: TRAILING
- Type that holds a large floating-point number: DOUBLE
- The name for math symbols like
+
and-
: OPERATOR - The ability to treat an object of one type as another type: POLYMORPHISM but I cannot find it -> I didn’t find it, but I found TYPECAST, which seems the nearest correct answer.
- Adds extra functionality to a type: EXTENSION
- The name for a function that exists inside a struct or class: METHOD
- Exits a loop immediately: BREAK
- Keyword for a function that can trigger errors: THROWS
- Key that lets us replace a method inherited from a superclass: OVERRIDE
- When one class builds on another: INHERITANCE
- Reads the length of a string: COUNT
- Apple’s all-in-one code editing environment: XCODE
- Operator that takes three operands: TERNARY
- Puts off work until later: LAZY ?? … or Dispatch? … not sure -> I found lazy!
- Name for a method called before class destruction: DEINIT
- Ordered collection of values stored in a single value: ARRAY
- A class that cannot be inherited from: FINAL
- Holds either true or false: BOOLEAN
Now, second rounds for the ones I didn’t get. All but one found! Third round … DONE! 50/50! Here is the fantastic picture!
Now I have to go out to buy some things for tomorrow’s trip! When I come back I want to work on the two articles of the Swiftoberfest and possibly prepare myself a bit for SwiftUI!
Back! 2 hours later and with a whole bunch of shops closed because in this part of Italy everything is resting on Monday as well … it seems that the economical crisis is not touching them enough…
So … now for the first article of the day, titled: “How to join an array of strings in a natural way”.
The second article of the day was on SwiftUI and titled “How to use Dynamic Type with a custom font”. I have to confess… whatever people say… I find SwiftUI very confusing and not at all easier or more direct than UIKit… it may look so in the beginning, but then it gets much more complicated, with all these modifiers and things that look like string interpolation but are other things completely.
I hope Daniel Steinberg’s workshop will shed some light on all this, along with the upcoming lesson by Paul.
I will not be able to follow the curriculum in the next 5 days because of traveling and of the conference in Bologna, but I will catch up from Sunday or Monday.
Let me know if you would like to have something specific covered from the conference.
Thank you for reading!
Good night, Swift world!
That’s it for today. Once more, you can find all the files I worked on today here.
If you like what I’m doing here please consider liking this article and sharing it with some of your peers. If you are feeling like being really awesome, please consider making a small donation to support my studies and my writing (please appreciate that I am not using advertisement on my articles).
If you are interested in my music engraving and my publications don’t forget visit my Facebook page and the pages where I publish my scores (Gumroad, SheetMusicPlus, ScoreExchange and on Apple Books).
You can also support me by buying Paul Hudson’s books from this Affiliate Link.
Anyways, thank you so much for reading!
Till the next one!