1

Why can we give an instance to variable in protocol extensions while we can't give an instance to variable in the protocol itself?

In the protocol, I can't give a variable new instance but when I make an extension from this protocol I can make a new instance to the variable ... and I don't know why I think the extension of the protocol will behave like protocol itself but it doesn't. while the class extension behaves like class itself.

As we can see in the image, we can't give variable instance but we can do it in the extension

1 Answers1

2

A protocol declares an abstract interface. The extension of a protocol declares default implementations.

Some programming languages do that differently (e.g. Java with the default keyword in an interface) but this was the syntax decision for Swift.

The reason why moving default implementations to an extension is better in Swift, is because the extension can have type contraints, therefore you can have different default implementations for different types.

For example:

protocol ErrorDisplaying {
    func showError(message: String)
}

extension ErrorDisplaying where Self: UIViewController {
   func showError(message: String) {
     let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
     present(alert, animated: true, completion: nil)
   }
}
Sulthan
  • 128,090
  • 22
  • 218
  • 270