23. Class and Protocols in Swift

Protocol is simply an interface of your class. The methods and the variables which you want to implement in your class, declare them in protocol and Swift will remind you to implement them all in your class.

Lets take an example of Person class which you have created in previous articles.

class Person {
    var name : String
    var age  : Int

    func getInfo() -> String{  }

For the simplicity, Person class contains two¬†variables and one method which are very easy to remember and easy to implement. What if this Person class contains name, age, height, weight, profession, education, town, city……. and so on, you need to remember all attributes and behaviours of this class so you could not miss any of them. Protocol helps to make sure that all required methods and variables are implemented.

Create a protocol and declare all required variables and methods which you need in Person class. Declaration of protocol is as follow:

protocol PersonProtocol{
    var name : String {get set}
    var age : Int {get set}
    func getInfo() -> String
    func jobTitle() -> String


PersonProtocol contains two variables name and age and two methods getInfo and jobTitle with return type string. Now you can implement this protocol on your Person class. The syntax is as follow:

class Person : PersonProtocol{


Once you will declare your class with protocol implemented, Swift compiler will immediately trigger an error

” ‘Person’ does not conform to protocol ‘PersonProtocol’ ”

Open assistant editor (cmd + alt + enter) and you will see the details of all members which your class must implement. Start declaring variables with init method of the class, implement getInfo method with string return type. As soon as you will implement required variables and methods, the error will reduce in assistant editor.

class Person : PersonProtocol{
    // properties
    var name : String
    var age  : Int
    init(personname : String, personage : Int){
        name = personname
        age  = personage
    // method from protocol
    func getInfo() -> String{
        return ("My name is \(name) and my age is \(age) years")
//    // method from protocol
//    func jobTitle() -> String {
//        return "poor programmer"
//    }


Right now compiler is asking for last method implementation jobTitle which is commented in your class. Just remove the comments and you are done with class and protocol.


Download file from GitHub