Swift Programming Tutorial: Protocols
How to specify the required properties and methods in Swift
Protocols in Swift act as blueprints specifying the necessary properties and methods an entity must adhere to. They offer a standardized framework tailored to specific tasks, contributing to enhanced code organization, easier maintenance, and increased flexibility. Developers can employ protocols to establish consistent behaviors across a variety of types. With this in mind, any type conforming to a protocol is expected to provide the necessary values for the properties defined in the protocol and implement the required methods.
While it may appear sophisticated, it’s not as intimidating as it sounds. As I mentioned earlier, it’s just a blueprint and doesn’t hold any value.
Protocols are easily declared using the protocol keyword. Here’s a simple example:
protocol ArmyComposition {
var general: String { get }
var size: Int { get set }
func attack()
func formation() -> String
mutating func recruit()
}
When defining properties within a protocol, it’s essential to specify whether a property is read-only (gettable) { get } or both readable and writable { get set }.
When defining functions within a protocol, it’s crucial to use the mutating keyword to specify whether…