Ray Wenderlich Functions and Types Course - Part 8

Just a little entry to try and maintain some momentum! Going to the next section now. Let's go!

Start Time - 20:47

Properties and Methods

This is the new chapter!

Stored Properties

I remember these from before. This is where you have variables/constants within a type and have the values set or they are entered on init.

Property Observers

Only useful for variable properties. These are only accessible when changing a value but not on init.

struct Wizard {
    
    var firstName: String {
        willSet {
            print("\(firstName) will be set to \(newValue)")
        }
        didSet {
            if firstName.contains(" ") {
                print("No spaces! \(firstName) is not a first name. You need to change to \(oldValue)")
                firstName = oldValue
            }
        }
    }
    var lastName: String
    

}


Type properties

Using static as the keyword. Only relevant within that type. 

So to access them you use the type itself rather than an instance of the type. 

You can use it as a constant or variable. As a var, you can then change the value of that type property.

static var ingredients = [
        "Polyjuice potions",
        "Rat's tails",
        "Bezoar"
        ] {
        didSet {
            print("Magical ingredients updating. Now we have \(ingredients)")
        }
    }

Enums can not have stored instance properties but can have stored type properties. 

Computed Properties

Last bit for now!

The get bit is all clear but the set bit is a tricky example. I've used set before without so much code. 

You can have get only but not set only. Only set with get. 

Set means that you can override the computed bit (the get code) with something else.


Lazy Properties

Just got time for this!

Lazy means it's not used until the first time you actually need it. 

So lazy is when you don't think you'll need it very often, it could take up a fair bit of space etc. 

Challenge!

Done the first bit no problems. For the next one it is putting in property observers but I already have get/set in there.... Those are for stored properties only!

OK, that second bit was fine - I had to swap the values over as the p.os. only work on stored properties, as expected!

Third challenge - not sure!

OK that was hard but now it makes sense. I needed to convert from function to computed property - by changing to var, then getting rid of the parameter list and changing a bit more syntax. 

Finish Time - 21:34 (approx 45 minutes)

I'm pretty good with these properties. Just need more practice. Done for today!

Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)