Home > Mobile >  how to defined protocol function with accessing class variable in swift
how to defined protocol function with accessing class variable in swift

Time:08-07

I have two classes that each has one identical function message in my example and my goal is to consolidate two functions into one to reduce the maintenance work. I have headed lots of document and found protocol may be the way to do it. However based on the example Example 1: Swift Protocol. i still do not understand how i can call the print function inside the message function under protocol Greet with accessing the variable name

protocol Greet {
  // blueprint of property
  var name: String { get }

  // blueprint of a method 
  func message() // ???? how to write the print function and access to name variable ??
} 

// conform class to Greet protocol
class Employee: Greet {

  // implementation of property
  var name = "Perry"

  // implementation of method
  func message() {
    print("Good Morning", name)
  }
}

class Student: Greet {

  var name = "student abc"

  func message() {
    print("Good Morning", name)
  }
}

var employee1 = Employee()
employee1.message()

var student = Student()
student.message()

CodePudding user response:

This is the beauty of protocol oriented programming. Your protocol extensions can define a default implementation where all types that conform to the protocol will inherit by default.

So if your protocol is:

protocol Greet {
  var name: String { get }
  func message()
} 

You can define a default implementation that your conforming types will inherit.

extension Greet {
    func message() {
        print("Good Morning", name)
    }
} 

And that way, your conforming types don't need to implement anything that has a default implementation defined in a protocol extension.

class Employee: Greet {
    var name = "Perry"
}

Usage would be like this:

let employee = Employee()
employee.message()

And that would print:

Good morning Perry

CodePudding user response:

Overview

You need to extend the protocol to provide a default implementation (you can't do it directly, because protocol is just a set of requirements, so extension can provide implementations)

Code

extension Greet {
    func message() {
        print("Good Morning", name)
    }
}

Reference

https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID277

  • Related