Dot Syntax in Swift

Can someone explain to me why we have to use Office.paperclipSalesRecord here instead of just paperclipSalesRecord? Isn’t it assumed were in the struct?

struct Office {    
    let paperclipCost = 10

    // Write your code below 💼
    static var paperclipSalesRecord = 0


    private var paperclipSales: Int  {
        willSet {
            print("We adjusted the sales to \(newValue) paperclips")
            if newValue > Office.paperclipSalesRecord{
            Office.paperclipSalesRecord = newValue
          }
        }
        didSet {
            print("Originally we sold \(oldValue) paperclips")
        }
    }
    
    var totalRevenue : Int {
        get {
            return (paperclipSales * paperclipCost) + getSecretRevenue()
        }
        set(newTotalRevenue) {
            paperclipSales = (newTotalRevenue - getSecretRevenue()) / paperclipCost
        }
    }

    init(paperclipSales: Int){
        self.paperclipSales = paperclipSales
    }
    
    private func getSecretRevenue() -> Int {
        return 100
    }
    
    func printTotalRevenue() {
        print("Our total revenue this month is \(totalRevenue)")
    }
    
}

var alphaOffice = Office(paperclipSales: 18)
alphaOffice.totalRevenue = 400
alphaOffice.printTotalRevenue()

It’s a static variable.

That means that regardless of any individual instantiation of your class/struct, the paperclipsSalesRecord will exist in memory and can be accessed. Another way to think about it is that there is no this.paperclipsSalesRecord for any particular Office, rather, one Office.paperclipsSalesRecord variable to represent the record for all office structs (whether or not this is good design, I will leave for you to decide after you look more into the matter).

Look up information and examples on static variables and static methods to get a better feel for how this works and when it’s useful/idiomatic, etc.

1 Like