Swift: Protocols

Programming

Swift: Protocols

ประกาศคุณสมบัติของ Type ที่ต้องการให้ Conform กับ Protocol นั้นๆ

12 เดือนที่ผ่านมา

1 min read

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!")
    }
}

Tags:

Swift