Protocols define a set of rules that classes, structs, or enums must follow. They make sure certain methods and properties are present.
Protocol requirements (methods and properties) in Swift
protocol SomeProtocol { var mustHaveProperty: Int { get set } func requiredMethod() -> String }
Properties in protocols can be read-only ({ get }) or read-write ({ get set }).
Methods in protocols only declare the signature, not the body.
protocol Vehicle { var numberOfWheels: Int { get } func drive() }
protocol Person { var name: String { get set } func greet() -> String }
protocol Logger { func log(message: String) }
This program defines a protocol Animal with a property and a method. The struct Dog follows the protocol by implementing the property and method. It then prints the dog's name and sound.
protocol Animal { var name: String { get } func sound() -> String } struct Dog: Animal { var name: String func sound() -> String { return "Woof!" } } let myDog = Dog(name: "Buddy") print("\(myDog.name) says \(myDog.sound())")
When a type adopts a protocol, it must implement all required methods and properties.
Properties can be declared as { get } or { get set } to control if they are read-only or read-write.
Protocols help write code that is easier to test and maintain.
Protocols define required methods and properties without implementation.
Types that adopt protocols must implement all requirements.
Use protocols to create flexible and reusable code.