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

Checkpoint 8: Protocols - A more elegant solution to Going Further

Forums > 100 Days of SwiftUI

In the Going Further section of Checkpoint 8, Paul challenges us to use "a protocol extension to provide a default implementation for printSummary()". Paul suggests adding a string property requirement to the protocol (for type of building) and then adding the property and giving it a default value in the declaration of each of the structs. Ignoring the fact that this property should have been declared as static* so as not to waste space in each and every instance of Building, there is an even better solution.

Instead of adding a property for type everywhere, just have printSummary() use Self.self instead of the type property. The default printSummary() will now look like:

// This will print the name of the Type.
func printSummary() {
        print("Talk to \(agent) to buy this \(Self.self) for $\(cost).")
}
  • In the case above where we used static, we get the name of the type by using Self.type.
    func printSummary() {
        print("Talk to \(agent) to buy this \(Self.type) for $\(cost).")
    }

3      

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.