Class communication w/ Protocols

In Swift, protocols define a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.

Here's an example of how two classes can communicate using a protocol in Swift:

// First, we define the protocol. A protocol can require specific
// properties, methods, and other requirements to be implemented.
protocol MessageDelegate: class {
  func didReceiveMessage(message: String)
}

// This is a simple class that sends messages to its delegate.
// The class has a property called "delegate" which should be an
// object that conforms to the MessageDelegate protocol.
class MessageSender {
  weak var delegate: MessageDelegate?

  func sendMessage(message: String) {
    // When the message is sent, we inform the delegate.
    delegate?.didReceiveMessage(message: message)
  }
}

// This is a simple class that receives messages from a MessageSender.
// The class conforms to the MessageDelegate protocol by implementing
// the required didReceiveMessage(message:) method.
class MessageReceiver: MessageDelegate {
  func didReceiveMessage(message: String) {
    print("Received message: \(message)")
  }
}

// Now we can create an instance of each class and have them communicate.
let sender = MessageSender()
let receiver = MessageReceiver()

// We set the receiver as the delegate of the sender.
sender.delegate = receiver

// Now when we call the sendMessage(message:) method on the sender,
// the receiver's didReceiveMessage(message:) method will be called.
sender.sendMessage(message: "Hello world!")

In this example, the MessageSender class sends messages to its delegate, which is an object that conforms to the MessageDelegate protocol. The MessageReceiver class adopts the MessageDelegate protocol and provides an implementation of the didReceiveMessage(message:) method, which simply prints the received message to the console.

When we create an instance of the MessageSender and MessageReceiver classes, we set the receiver as the delegate of the sender. Then, when we call the sendMessage(message:) method on the sender, the receiver's didReceiveMessage(message:) method is called, and the message is printed to the console.

This is just a simple example, but it demonstrates how protocols can be used to enable communication between classes in Swift. Protocols can be very powerful and provide a lot of flexibility in your code.

Previous
Previous

What are delegates?

Next
Next

Understanding Enums