1. Introduction
Protocols in Swift are similar to interfaces in many other programming languages. They define a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. Protocols can be adopted by classes, structures, or enumerations to provide an actual implementation of those requirements. Moreover, protocols can be used as a type to define a set of requirements that a particular object needs to satisfy.
2. Source Code Example
// Protocol Definition protocol AnimalProtocol { var name: String { get set } var canFly: Bool { get } func makeSound() -> String } // Class that adopts the protocol class Dog: AnimalProtocol { var name: String var canFly: Bool { return false } init(name: String) { self.name = name } func makeSound() -> String { return "Bark" } } // Another class that adopts the protocol class Bird: AnimalProtocol { var name: String var canFly: Bool { return true } init(name: String) { self.name = name } func makeSound() -> String { return "Chirp" } } // Create instances and invoke protocol methods/properties let dog = Dog(name: "Buddy") print("\(dog.name) makes sound: \(dog.makeSound()) and can fly: \(dog.canFly)") let bird = Bird(name: "Tweety") print("\(bird.name) makes sound: \(bird.makeSound()) and can fly: \(bird.canFly)")
Output:
Buddy makes sound: Bark and can fly: false Tweety makes sound: Chirp and can fly: true
3. Step By Step Explanation
1. We start by defining a protocol called AnimalProtocol which has a variable name, a computed property canFly, and a function makeSound().
2. Next, we create a Dog class that adopts and conforms to the AnimalProtocol. The Dog class provides concrete implementations for all the requirements defined in the protocol.
3. Similarly, we define a Bird class that also conforms to AnimalProtocol.
4. We then create instances of the Dog and Bird classes and call their respective methods and properties, demonstrating that they both adhere to the contract specified by the AnimalProtocol.
Comments
Post a Comment