Swift 4 basics - protocols
Protocols: Something like interfaces, where we describe the methods, properties and requirements of a type without providing implementation. Here is how to define a protocol: protocol MyProtocol{ var a: Int{get set} var b: String{get set} var readOnlyVar: String{get} //var a, b, and c will have to be listed as properties in any class implementing the protocol func getBSquared() -> Int //this method will have to be defined and implemented in the class that implements this protocol } To implement it in a structure: struct MyStruct: MyProtocol{} A structure can implement more than one protocol: struct MyStruct: Proto1, Proto2, Proto3{} If a class both implements and inherits, we can define the class by inheriting first, then by implementing: Class MyClass: TheParentClass, Proto1, Proto2{} Protocols can be used as types var aProto = Proto1 Can be stored in arrays: var proto: [Proto1] = [] You however, cannot create an instance of a protocol. You can create a...
Comments
Post a Comment