What is Protocols in Swift?
Swift, protocols are a powerful feature that allows you to define a set of rules or a blueprint that types (classes, structs, or enums) can adopt and conform to. Protocols are similar to interfaces in Java but offer additional features and flexibility.
Let's break down the key points of protocols in swift.
1. Definition of a Protocol:
A protocol is a blueprint for methods, properties, and other requirements that a conforming type must implement.
protocol Vehicle
{
var numberOfWheels: Int { get }
func start()
func stop()
}
2. Protocol Functions Without Body:
Protocols can have methods without a predefined body, leaving the implementation to the conforming types.
protocol Greetable
{
func greet()
}
struct Person: Greetable
{
func greet()
{
print("Hello!")
}
}
3. Creating Rules and Conforming to a Protocol:
Types conform to a protocol by implementing its required methods and properties.
protocol Vehicle
{
var numberOfWheels: Int { get }
func start()
func stop()
}
struct Car: Vehicle
{
var numberOfWheels: Int = 4
func start()
{
print("Car engine started")
}
func stop()
{
print("Car engine stopped")
}
}
4. Inheritance through Protocols:
Although structures don't support inheritance, they can conform to protocols, providing a form of inheritance.
领英推荐
struct Bike: Vehicle
{
var numberOfWheels: Int = 2
func start()
{
print("Bike engine started")
}
func stop()
{
print("Bike engine stopped")
}
}
5. Protocol Function Implementation with Extension:
You can use extensions to provide default implementations for protocol methods.
protocol Playable
{
func play()
}
extension Playable
{
func play()
{
print("Playing...")
}
}
struct MusicPlayer: Playable {}
6. Get and Set in Protocol:
Protocols can include properties with getters and setters.
protocol AdjustableVolume
{
var volume: Int { get set }
}
class Speaker: AdjustableVolume
{
var volume: Int = 50
}
7. Mutable Functions in Protocols:
Protocols can declare mutating methods for value types (structs and enums) that need to modify their instance.
protocol Incrementable
{
mutating func increment()
}
// Conform a struct to the Incrementable protocol
struct Counter: Incrementable
{
var value: Int = 0
// Implement the mutating method to increment the value
mutating func increment()
{
value += 1
}
}
// Create an instance of the Counter
var myCounter = Counter()
print("Initial value: \(myCounter.value)")
// Call the mutating method to increment the value
myCounter.increment()
print("After incrementing: \(myCounter.value)")
8. Using Protocols for Delegation:
You can use protocols for delegation, allowing one class to delegate responsibilities to another.
protocol AlarmDelegate
{
func alarmTriggered()
}
class SecuritySystem
{
var delegate: AlarmDelegate?
func triggerAlarm()
{
// Code to trigger the alarm
delegate?.alarmTriggered()
}
}
class HouseOwner: AlarmDelegate
{
func alarmTriggered()
{
print("House alarm triggered! Investigating...")
}
}