UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Static properties and methods

Forums > 100 Days of SwiftUI

https://www.hackingwithswift.com/sixty/7/11/static-properties-and-methods

Hi

In this specific lesson in the example inside the init() the property 'name' uses 'self.name' as he is part of the struct.

Then why the property 'classSize' uses the name of the struct?

Didn't get why I can't just use only classSize or 'self.classSize'.

struct Student {
    static var classSize = 0
    var name: String

    init(name: String) {
        self.name = name
        Student.classSize += 1
    }
}

3      

It's because classSize is a static property, meaning it belongs to the type not to any given instance of that type.

name is an instance property, meaning each Student you create has its own name property. Since self here refers to a given instance of Student, you access this property with self.name.

classSize is a static property, meaning every instance of Student that you create shares the same classSize property. Since this property doesn't belong to any one instance of Student but rather to the type itself, you access it through the type name, i.e. Student.classSize.

5      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.