Protocol เปรียบเสมือนข้อกำหนดว่า ถ้าหาก Class , Struct หรือ Enum ไหนนำ Protocol นี้ไปใช้ จะต้องทำตามที่ Protocol นั้นกำหนด โดยการนำไปใช้จะเรียกว่าการ Conform
ประกาศ Protocol
protocol Animal {
var name: String { get set }
func makeSound()
}
Conform Protocol
struct Dog: Animal {
var name: String
func setName(name: String) {
self.name = name
}
func makeSound() {
print("Woof!")
}
}