Protocol
Protocol เป็นเหมือนพิมพ์เขียวที่ระบุข้อกำหนดต่าง ๆ สำหรับการทำงานหนึ่ง ๆ เช่น ระบุ method ที่ต้องใช้ หรือ properties ที่จำเป็น
ผู้ที่ implement การทำงานของพิมพ์เขียวเป็นได้ทั้ง Class, Struct หรือ Enum เราจะเรียก type ที่ทำงานได้ตามพิมพ์เขียวนี้ว่า type นี้ conform protocol
การประกาศใช้ เริ่มด้วย protocol จากนั้นคือชื่อของ protocol ตามด้วยข้อกำหนดของ protocol
protocol SomeProtocol {
// protocol definition goes here
}เช่น
protocol ItemDiscribable {
var description: String { get }
}
protocol Togglable {
mutating func toggle()
}การประกาศว่า conform protocol ใช้ : หลังชื่อของ Struct, Enum หรือ Class แล้วตามด้วย ชื่อของ protocol ที่เราต้องการ conform ซึ่งเราอาจ conform ได้มากกว่าหนึ่งอัน
struct SomeStructure: FirstProtocol, AnotherProtocol {
// structure definition goes here
}
enum SomeEnum: FirstProtocol {
// enum definition goes here
}สำหรับ class ที่ต้องการ interit จาก class อื่น เนื่องจากการ inherit สามารถทำได้จาก parent เดียว จึงให้ใส่ชื่อ class นั้นก่อน แล้วจึงตามด้วย protocol
ตัวอย่างการ conform protocol จาก TapSwitch ที่เราเขียนกันไปก่อนหน้านี้ เนื่องจากเรา implement ของที่ protocol เราต้องการอยู่แล้ว เราจึงแค่ใส่ชื่อ protocol เพิ่มในการประกาศ Enum
ทำให้เราสามารถสร้าง Array เป็น type ของ protocol และเก็บของที่ต่างกันไว้รวมกันได้
Last updated