Programming

Swift: Protocols

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

29 กรกฎาคม 20231 นาที
0
Swift: Protocols
Table of Contents

Protocol เปรียบเสมือนข้อกำหนดว่า ถ้าหาก Class , Struct หรือ Enum ไหนนำ Protocol นี้ไปใช้ จะต้องทำตามที่ Protocol นั้นกำหนด โดยการนำไปใช้จะเรียกว่าการ Conform

ประกาศ Protocol

Swift Logo
protocol Animal { var name: String { get set } func makeSound() }

Conform Protocol

Swift Logo
struct Dog: Animal { var name: String func setName(name: String) { self.name = name } func makeSound() { print("Woof!") } }
Tags:Swift

คลิกเพื่อแสดงความคิดเห็น