When writing a struct, class, or enum it may be helpful to divide the code into several different sections. By using an extension, you can continue writing the definition of a struct, class, or enum anywhere in your codebase.
struct Cat { let name: String let age: Int } extension Cat { static let famousCats = [ Cat(name: "Stubbs", age: 20), Cat(name: "Sweet Tart", age: 12), Cat(name: "Hank the Cat", age: 13) ] } print(Cat.famousCats.count) // prints 3
Code that’s written in an extension will behave exactly the same as if it was defined in the original struct. You can even extend structs, classes, and enums from the Swift Standard Library!
extension Int { var isEven: Bool { isMultiple(of: 2) } } let catCount = 3 print(catCount.isEven) // prints false
The only thing that you can’t do in extensions is create stored properties:
struct Cat { let name: String let age: Int } extension Cat { var numberOfLegs: Int // ERROR: Extensions must not contain stored properties }
This restriction ensures that adding an extension will never cause your code to not compile by adding new requirements. Instead, you can add computed properties:
struct Cat { let name: String let age: Int } extension Cat { var numberOfLegs: Int { return 4 } }
Let’s try adding an extension to our Office
!
Instructions
Add an extension to the Office
struct.
In the extension add a static method named printCurrentRecord
that prints “The current record for paperclip sales is paperclipSalesRecord
” using string interpolation.
In the extension, add a computed property named paperclipColor
of type String
that returns “gray”.
Call the new static method printCurrentRecord
on Office
.
Print the color of alphaOffice
‘s paperclips in the form “Alpha Office’s paperclips are paperclipColor
“ using string interpolation.