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

Checkpoint 8

Paul Hudson    @twostraws   

Updated for Xcode 15

Now that you understand how protocols and extensions work, it’s time to pause our learning and take on a challenge so you can put it all into practice.

Your challenge is this: make a protocol that describes a building, adding various properties and methods, then create two structs, House and Office, that conform to it. Your protocol should require the following:

  1. A property storing how many rooms it has.
  2. A property storing the cost as an integer (e.g. 500,000 for a building costing $500,000.)
  3. A property storing the name of the estate agent responsible for selling the building.
  4. A method for printing the sales summary of the building, describing what it is along with its other properties.

I’ll provide some hints in a moment, but first I recommend you go ahead and try it yourself.

Hacking with Swift+ subscribers can get a complete video solution for this checkpoint here: Solution to Checkpoint 8. If you don’t already subscribe, you can start a free trial today.

Still here? Okay, here are some hints:

  1. Start by designing the protocol fully before you go near any structs.
  2. Remember you can’t provide implementations for methods in your protocol.
  3. You get to decide whether your properties should be get-only or have getters and setters. For example, maybe the number of rooms is constant, but perhaps you also want to take into account someone adding an extension.
  4. You can control the read-write status of a property using { get } or { get set }.

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.8/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.