![]() ![]() Then add this code to it:īuild the playground with Command-Shift-Return to make sure that it compiles properly. Time to get hands-on and take this racing concept for a spin.īegin by opening Xcode and then creating a new playground named ayground. With protocols, you can create a FlyingCar class that conforms to both MotorVehicle and Aircraft. ![]() Instead, you add different building blocks until your object is ready.Ĭonverting base classes into protocols solves your video game dilemma. When you add new functionality by conforming an object to a protocol, you don’t build a whole new object. Think of protocols as building blocks of functionality. When writing an app this way, your code becomes more modular. Only class types can use base classes and inheritance.Īn advantage of protocols in Swift is that objects can conform to multiple protocols. Swift lets you specify these interface guarantees on class, struct and enum types. Protocols allow you to group similar methods, functions and properties. Who will save your racing game from this disastrous dilemma? Protocol-oriented programming to the rescue! How can your flying cars inherit from both MotorVehicle and Aircraft? Do you create another base class that merges the two functionalities? Probably not, since there’s no clean and easy way to do this. Swift doesn’t support multiple inheritance. You think, “This is going great.” But wait! Your racing game is set in the year 30XX, and some cars can fly. You also design a base class called Aircraft that Plane inherits from. Car and Motorcycle then inherit from MotorVehicle. You’ll work on that later.Īs you code, you notice that Car and Motorcycle share some functionality, so you create a base class called MotorVehicle and add them to it. You start programming your game by creating classes for each vehicle. The base classes would have the “drive” and “pilot” logic in them. They can even ride different birds - because it’s a video game - and you can drive whatever you want! The key here is that there are lots of different “things” that can be driven or piloted.Ī common approach for this type of app is object-oriented programming, where you can encapsulate all of the logic inside base classes that other classes then inherit from. You want players to be able to drive cars, ride motorcycles and pilot planes. Imagine you’re developing a racing video game. ![]() If you are new to Swift development, check out Swift Tutorial for Beginners and Swift Generics Tutorial: Getting Started beforehand. Note: This tutorial assumes you know the basics of Swift development and more advanced topics like generics. ![]()
0 Comments
Leave a Reply. |