Skip to content

Instantly share code, notes, and snippets.

@lucianoschillagi
Last active September 7, 2024 14:57
Show Gist options
  • Save lucianoschillagi/9e734c57f39def1476f8b21ae2b662b4 to your computer and use it in GitHub Desktop.
Save lucianoschillagi/9e734c57f39def1476f8b21ae2b662b4 to your computer and use it in GitHub Desktop.
class-only protocols
import Foundation
// Define a class-only protocol conforming 'Vehicle' to 'AnyObject'.
protocol Vehicle: AnyObject {
var numberOfWheels: Int { get }
func drive()
}
// Define a class that adopts the protocol.
class Car: Vehicle {
var numberOfWheels = 4
func drive() {
print("Driving a car with \(numberOfWheels) wheels.")
}
}
// NOTE: If you convert 'Car' in a struct the compiler will give you an error
// because the protocol 'Vehicle' is a class-only protocol (AnyObject).
// Create an instance of the Car class and call the methods
let myCar = Car()
myCar.drive()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment