Skip to Content

Protocols trong Swift

1. Giới thiệu

Protocol định nghĩa blueprint của methods, properties và requirements.

2. Khai báo Protocol

protocol Drawable { func draw() } struct Circle: Drawable { func draw() { print("Drawing circle") } } struct Square: Drawable { func draw() { print("Drawing square") } }

3. Property Requirements

protocol Named { var name: String { get } var fullName: String { get set } } struct Person: Named { var name: String var fullName: String }

4. Method Requirements

protocol Togglable { mutating func toggle() } struct Switch: Togglable { var isOn = false mutating func toggle() { isOn.toggle() } }

5. Initializer Requirements

protocol Initializable { init(value: Int) } class MyClass: Initializable { var value: Int required init(value: Int) { self.value = value } }

6. Protocol Inheritance

protocol Animal { var name: String { get } } protocol Pet: Animal { var owner: String { get } } struct Dog: Pet { var name: String var owner: String }

7. Default Implementation

protocol Greetable { var name: String { get } func greet() } extension Greetable { func greet() { print("Hello, \(name)!") } } struct Person: Greetable { var name: String // greet() có implementation mặc định }

8. Protocol as Type

func render(_ drawable: Drawable) { drawable.draw() } let shapes: [Drawable] = [Circle(), Square()] shapes.forEach { $0.draw() }

9. Protocol Composition

protocol Named { var name: String { get } } protocol Aged { var age: Int { get } } func celebrate(_ person: Named & Aged) { print("Happy \(person.age)th birthday, \(person.name)!") } struct Person: Named, Aged { var name: String var age: Int }

10. Common Protocols

// Equatable struct Point: Equatable { var x: Int var y: Int } Point(x: 1, y: 2) == Point(x: 1, y: 2) // true // Hashable struct Person: Hashable { var name: String } // Codable struct User: Codable { var id: Int var name: String } // CustomStringConvertible struct Item: CustomStringConvertible { var description: String { "Item" } }

📝 Tóm tắt

  • Protocol định nghĩa contract
  • { get }{ get set } cho properties
  • Extension cung cấp default implementation
  • Protocol composition với &
  • Dùng như type cho polymorphism
  • Common: Equatable, Hashable, Codable
Last updated on