Bob Lee Course Part 6 (lessons 9 and 10)

So back to Bob's course we go! Last time I spent a fair old while focusing on consolidation, which was really worthwhile. I definitely understand type casting, error handling, generics...all of that better than before! Well, here we go. Onwards to the next lesson!

Start Time 19:32

Subscripts


So Bob refers to this as wanting to use a shortcut for using a method when creating an object....













So here is an example of an array of days within a WeekDays struct, then a subscript used to return a string.

struct HealthInfo {
    
    var info = ["Height": 176, "Weight": 67.4, "Body Fat": 12.5]
    
    subscript(key: String) -> Double {
        if let newInfo = info[key] {
            return newInfo
        } else {
            return 0
        }
    }

}

An example above - all from Bob. So, in this case, the subscript means that you can use the key (Height, Weight or Body Fat) to then access what the double value is. This is unwrapped as dictionaries contain optionals (the if let optional binding used).

let info1 = HealthInfo()

info1["Height"]

Not COMPLETELY sure about subscripts. I will need more practice. Anyway, moving on..

Class vs Struct

So I know a bit about this. Classes are more complex and are better when there are lots of possibilities. Structs are better for certain mathematical constructs and so on. 

class HumanClass {
    
    var name: String
    init(name: String) {
        self.name = name
    }
}


var humanObject = HumanClass(name: "Josh")

Straightforward recap here. 

I know where this is going. Class is a REFERENCE type and struct is VALUE. This means that all references of a value change with classes...

var humanObject = HumanClass(name: "Josh")

var newHumanObject = humanObject

newHumanObject.name = "Steve"

So in theory, the name of humanObject should change to Steve too!

So the key difference here is that a struct object would not change the original value. 

Another key difference for mutability - you CAN change the value of a constant property with classes. You cannot do this with structs. Interesting. 

OK so classes are slower as they have to follow lines of inheritance. Structs don't so they are faster. 

Apparently struct is 'Swift oriented'. This is a good point - ints, strings etc. are all technically types of struct. 

Finish Time - 20:24 (52 minutes total)

Good stuff! It was fun to compare structs and classes. That's opened my eyes up as to why classes can be tricky and actually difficult to use - that has been fine before, in terms of memory etc. Interesting stuff here. I need to know more about subscripts - this will be perfect in terms of going through the consolidation bits etc. 

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)