|
Can anyone help me evaluate if what I'm doing here is correct?
|
|
@swiftHacker wonders if they're following the protocol:
Well done!I ran your code in a Playground and both the structs So I'd say "yes, what you did is correct." Keep CodingHowever, you may not appreciate the full value of a protocol's requirement to have a particular function. Both Look at the code below. I implemented a different version of
|
|
I see. So basically, I can still change what the function does I only need to ensure that the function name is the same as what's in the protocol. I can then somehow "override" it (change what the function does) so that it can be something else entirely. Is my understanding correct? |
|
A follow on question:
Yes! Comparable ProtocolThink of the It allows you to write a custom struct for your application (House, Lego, Employee, Spaceship) and enjoy the benefits of being able to compare and sort them using built in Swift capabilities. Sorting two objects is subjective. The rules change for every object in existence. So the Try it!First tell your
Xcode will complain that the Allow Xcode to automagically fix the error by adding the proper protocol stub. You should now see this...
lhs? rhs? What does this even mean? Your JobYou are the programmer. You speak to your users. Get their requirements and code them! It is YOUR JOB to determine how you compare two Office buildings. If I were to put two offices in front of you, what is YOUR criteria for sorting them? As an example, let's go with NUMBER OF FLOORS. lhs is shorthand for Left Hand Side, rhs is shorthand for Right Hand Side. If the right hand building has MORE FLOORS than the left hand building, then the right hand building is "larger" than the right hand one. So code your
How does this help me?Now that you've defined what a office building is (floors, offices, cost, etc) You can now create a collection of offices in your application. Because your Try this....
HomeworkImagine you created a Now think! How would YOU sort the Lego bricks in the And keep this in mind! The rules you use to sort two Lego bricks are wildly different from the way I would sort two Student structs. Yet we can both use the array's Keep Coding! |
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
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.
Link copied to your pasteboard.