What is Protocols in Swift?

Swift, protocols are a powerful feature that allows you to define a set of rules or a blueprint that types (classes, structs, or enums) can adopt and conform to. Protocols are similar to interfaces in Java but offer additional features and flexibility.

Let's break down the key points of protocols in swift.

1. Definition of a Protocol:

A protocol is a blueprint for methods, properties, and other requirements that a conforming type must implement.

protocol Vehicle 
{ 
      var numberOfWheels: Int { get } 
      func start()
      func stop() 
}        

2. Protocol Functions Without Body:

Protocols can have methods without a predefined body, leaving the implementation to the conforming types.

protocol Greetable

 { 
     func greet() 
} 

struct Person: Greetable 
{ 
       func greet()
        { 
            print("Hello!") 
         } 
}        

3. Creating Rules and Conforming to a Protocol:

Types conform to a protocol by implementing its required methods and properties.

protocol Vehicle 
{ 
      var numberOfWheels: Int { get } 
      func start()
      func stop() 
}
struct Car: Vehicle
 {
    var numberOfWheels: Int = 4
    
    func start() 
    {
        print("Car engine started")
    }
    
    func stop() 
   {
        print("Car engine stopped")
    }
}        

4. Inheritance through Protocols:

Although structures don't support inheritance, they can conform to protocols, providing a form of inheritance.

struct Bike: Vehicle 
{
    var numberOfWheels: Int = 2
    
    func start()
   {
        print("Bike engine started")
    }
    
    func stop() 
   {
        print("Bike engine stopped")
    }
}        

5. Protocol Function Implementation with Extension:

You can use extensions to provide default implementations for protocol methods.

protocol Playable 
{
    func play()
}

extension Playable
 {
    func play()
    {
        print("Playing...")
    }
}

struct MusicPlayer: Playable {}        

6. Get and Set in Protocol:

Protocols can include properties with getters and setters.

protocol AdjustableVolume 
{
    var volume: Int { get set }
}

class Speaker: AdjustableVolume
 {
    var volume: Int = 50
 }        

7. Mutable Functions in Protocols:

Protocols can declare mutating methods for value types (structs and enums) that need to modify their instance.

protocol Incrementable
 {
    mutating func increment()
}

// Conform a struct to the Incrementable protocol
struct Counter: Incrementable
 {
    var value: Int = 0
    
    // Implement the mutating method to increment the value
    mutating func increment()
   {
        value += 1
    }
}

// Create an instance of the Counter
var myCounter = Counter()
print("Initial value: \(myCounter.value)")

// Call the mutating method to increment the value
myCounter.increment()
print("After incrementing: \(myCounter.value)")        

8. Using Protocols for Delegation:

You can use protocols for delegation, allowing one class to delegate responsibilities to another.

protocol AlarmDelegate 
{
    func alarmTriggered()
}

class SecuritySystem 
{
    var delegate: AlarmDelegate?
    
    func triggerAlarm() 
    {
        // Code to trigger the alarm
        delegate?.alarmTriggered()
    }
}

class HouseOwner: AlarmDelegate 
{
    func alarmTriggered() 
   {
        print("House alarm triggered! Investigating...")
    }
}        

要查看或添加评论,请登录

rama sharma的更多文章

  • Options for managing commits in GitHub Desktop

    Options for managing commits in GitHub Desktop

    In GitHub Desktop, you have several options for managing commits, making it easy to interact with your repository and…

  • How to Reorder Commits in GitHub Desktop

    How to Reorder Commits in GitHub Desktop

    Create Files and Commit: Create a file and perform the first commit. Create another file and perform a second commit.

  • Different Ways to Ignore Files Using GitHub Desktop

    Different Ways to Ignore Files Using GitHub Desktop

    Manually Add Folders and Files to .gitignore from GitHub Desktop Changes Section: Navigate to the Changes tab in GitHub…

  • Adding a repository from your local computer to GitHub Desktop

    Adding a repository from your local computer to GitHub Desktop

    Open GitHub Desktop. Click on File > Add Local Repository > Create a Repository.

  • How to Perform Git Clone Using GitHub Desktop?

    How to Perform Git Clone Using GitHub Desktop?

    Git clone is the process of creating a local copy of a repository hosted on GitHub, just like the Git command line git…

  • "Let's start exploring GitHub file -> Options" menu:

    "Let's start exploring GitHub file -> Options" menu:

    Here’s an explanation of the GitHub file -> Options" menu: a) Account This section is where you manage your GitHub…

  • How to Install GitHub Desktop on Windows?

    How to Install GitHub Desktop on Windows?

    System Requirements Operating System: Windows 10 or newer. Processor: 64-bit processor.

  • What is GitHub Desktop?

    What is GitHub Desktop?

    GitHub Desktop is a free and open-source application that provides a user-friendly graphical user interface (GUI) for…

  • C# - What is OOP?

    C# - What is OOP?

    In C#, Oops stands for Object-Oriented Programming. It's a programming paradigm based on the concept of "objects,"…

  • Control statements

    Control statements

    Control statements allows the smooth flow of a program. A control statement in c# is a statement that determines…

社区洞察

其他会员也浏览了