The Language Reference & Guide
- Welcome to Emojicode
- Syntax
- The Basics
- Literals
- Variables and Assignment
- Control Flow
- Classes & Value Types
- Overloading
- Operators
- Optionals
- Errors
- Inheritance and Overriding
- Protocols
- Enumerations
- Types and Namespaces
- Types as Values
- Documentation
- Generics
- Callables
- Packages
- Threads
- Safe and Unsafe Code
- Memory Management
- References
- Appendix: The Emojicode Compiler
Protocols
Protocols define methods for special functionality. Protocols only describe the methods a type must offer to support this functionality. Types can conform to protocols by implementing all methods and declaring the conformation.
Defining a protocol defines a type. All types that agree to that protocol are compatible to this type.
Declaration
The syntax to define a protocol is simliar to the way of defining a class:
protocol βΆ π type-identifier [generic-parameters] π protocol-body π
protocol-body βΆ protocol-method | protocol-method protocol-body
protocol-method βΆ [documentation-comment] [β οΈ] mood emoji-id arguments return-type
For example:
π πΏ π
βοΈπΆ
π
Here we declared a protocol named πΏ. All classes that conform to this protocol will have to implement the method πΆ. This protocol doesnβt tell us anything about the actual type but we do know that all types that conform to πΏ are capable of playing music and therefore must provide the πΆ method.
You can use the βοΈ to require instance methods inside the π body. At present it is not possible to require initializers or type methods.
Conforming
To make a class conform to a protocol you must declare that it conforms to the protocol using the conformance syntax:
protocol-conformance βΆ π type
Let us declare a class that conforms to πΏ.
π π± π
π πΏ
π ππ
βοΈ πΆ π
π π€Lalalalaπ€βοΈ
π
π
The actual statement to achieve this is π protocolName
, where protocolName must be the type name of the protocol, and can occur everywhere in the class body.
Promises also apply when implementing protocol methods. An extension can also make a class conform to a protocol.
Calling Methods on Values of Protocol Type
Methods on protocol values are called like any other methods:
ππ cd_like πΏ
ππ±βοΈ β‘οΈ π cd_like
πΆ cd_likeβοΈ
Multiprotocols
It might happen that youβll need to deal with values of types that implement several protocols. For instance, you might want to provide a method which requires an argument that can be accessed with π½οΈ and can be compared as defined by the πΏ protocol. This is where multiprotocols are of service.
You can use a multiprotocol type like so:
π± π½οΈππ‘π πΏ π±
For instance, when declaring the arguments to a method:
βοΈ π a π± π½οΈππ‘π πΏ π± π
π ...
π
As expected, a
can now be used both as an instance of a type conforming to π½οΈππ‘π and as an insatnce of a type conforming to πΏ.