Learn

Up until this point, we have always associated properties with an instance of a struct. However, it is also possible to define a property that is associated directly with the struct itself. Such a property is known as a type property.

A type property can be useful in cases where there is some value that we want to be consistent regardless of any instance of our struct. This might be a constant value, but it can also be a variable. Usually, the value is associated with that type of object for a specific logical or informational reason. For example, Double.pi is a type property that retrieves the value of pi from the built-in Double structure in Swift.

Let’s say we want to create a variable type property that stores the value of oldestCat. It will be updated when a specific cat breaks the age record, but it will hold true across all cats. We define a type property using the static keyword:

struct Cat { static var oldestCat : Int = 0 }

Since type properties aren’t tied to any instance of the struct, we use dot syntax on the type itself to access them:

Cat.oldestCat = 38 print(“So far the oldest cat we have seen is \(Cat.oldestCat) years old.”) // Prints: So far the oldest cat we have seen is 38 years old.

Methods can also be declared as static. These are called on the class, structure, or enumeration itself rather than an instance.

struct Cat { static func displayDescription() { print("Cat's are great pets!") } } Cat.printDescription() // prints Cat's are great pets!

Instructions

1.

Create a variable Int type property named paperclipSalesRecord with an initial value of 0.

2.

In the willSet property observer of paperclipSales, check if the newValue is greater than paperclipSalesRecord. If newValue is greater, assign it to paperclipSalesRecord

3.

Print the value of paperclipSalesRecord to the console.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?