What is Protocol Oriented Programming in Swift? What added value does it bring?

前端 未结 5 943
耶瑟儿~
耶瑟儿~ 2020-12-02 13:41

From Apple\'s own website: \"At the heart of Swift\'s design are two incredibly powerful ideas: protocol-oriented programming and first class value semantic

5条回答
  •  失恋的感觉
    2020-12-02 14:00

    Adding to the above answer

    Protocol is a interface in which signature of methods and properties are declared and any class/struct/enum subclassing the enum must have to obey the contract means they have to implement all the methods and properties declared in superclass protocol.

    Reason to use Protocol

    Classes provide single inheritance and struct doesn't support inheritance. Thus protocols was introduced.

    Extension The methods declare inside the protocol can be implemented inside the extension to avoid the redundancy of the code in case protocol is being inherited in multiple class / struct having same method implementation. We can call the method by simply declaring the object of struct/enums. Even we can restrict the extension to a list of classes, only restricted class will be able to use the method implemented inside the extension while rest of the classes have to implement method inside own class.

    Example

    protocol validator{
    
        var id : String{ get }
        func capitialise()-> (String)
    
    }
    
    extension validator where Self : test{
        func capitialise() -> String{
            return id.capitalized
        }
    }
    
    class test : validator {
    
        var id: String
    
        init(name:String) {
            id = name
        }
    }
    
    let t = test(name: "Ankit")
    t.capitialise()
    

    When to use In OOP suppose we have a vehicle base class which is inherited by the airplane, bike, car etc. Here break, acceleration may be common method among three subclass but not the flyable method of airplane. Thus if we are declaring flyable method also in OOP, the bike and car subclass also have the inherit flyable method which is of no use for those class. Thus in the POP we can declare two protocols one is for flyable objects and other is for break and acceleration methods. And flyable protocol can be restricted to use by only the airplane

提交回复
热议问题