The syntax for conforming to a protocol is to add the protocol name after the type name, separated by a colon. Swift classes, structures, and enumerations can all conform to protocols. Type properties and type methods must be prefixed with the static keyword when they are defined in a protocol. Mutating methods must use the mutating keyword to enable value types (structs and enums) to adopt the protocol. Method requirements in a protocol are declared with just a method signature, omitting the curly braces and method body, and default parameter values are not allowed. Property requirements in a protocol are always declared as variables, and specify whether a property must be gettable or gettable and settable. You simply use the keyword protocol, followed by the protocol name, and a set of curly braces within which you define the protocol properties and methods. The syntax used to define a protocol is very similar to defining a class or structure. When types satisfy that protocol they are said to conform to that protocol. You can define a protocol to specify the interface that you want certain types to satisfy. This makes protocols ideal for delegation, which is a design pattern wherein a set of specific responsibilities are handed off to an instance of a protocol conforming type, referred to as the delegate. In this way, a protocol is a form of encapsulation, which allows you to interact with the interface without concern for the particular implementation type, which may be injected at runtime. The protocol can then be adopted by a class or structure to provide the actual implementation of that functionality. A protocol is an interface that defines a set of properties and methods which are necessary for a particular piece of functionality.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |