Last active
September 7, 2024 14:57
-
-
Save lucianoschillagi/9e734c57f39def1476f8b21ae2b662b4 to your computer and use it in GitHub Desktop.
class-only protocols
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| // Define a class-only protocol conforming 'Vehicle' to 'AnyObject'. | |
| protocol Vehicle: AnyObject { | |
| var numberOfWheels: Int { get } | |
| func drive() | |
| } | |
| // Define a class that adopts the protocol. | |
| class Car: Vehicle { | |
| var numberOfWheels = 4 | |
| func drive() { | |
| print("Driving a car with \(numberOfWheels) wheels.") | |
| } | |
| } | |
| // NOTE: If you convert 'Car' in a struct the compiler will give you an error | |
| // because the protocol 'Vehicle' is a class-only protocol (AnyObject). | |
| // Create an instance of the Car class and call the methods | |
| let myCar = Car() | |
| myCar.drive() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment