Protocols
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”Protocol định nghĩa blueprint của methods, properties và requirements.
2. Khai báo Protocol
Phần tiêu đề “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
Phần tiêu đề “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
Phần tiêu đề “4. Method Requirements”protocol Togglable { mutating func toggle()}
struct Switch: Togglable { var isOn = false
mutating func toggle() { isOn.toggle() }}5. Initializer Requirements
Phần tiêu đề “5. Initializer Requirements”protocol Initializable { init(value: Int)}
class MyClass: Initializable { var value: Int
required init(value: Int) { self.value = value }}6. Protocol Inheritance
Phần tiêu đề “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
Phần tiêu đề “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
Phần tiêu đề “8. Protocol as Type”func render(_ drawable: Drawable) { drawable.draw()}
let shapes: [Drawable] = [Circle(), Square()]shapes.forEach { $0.draw() }9. Protocol Composition
Phần tiêu đề “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
Phần tiêu đề “10. Common Protocols”// Equatablestruct Point: Equatable { var x: Int var y: Int}Point(x: 1, y: 2) == Point(x: 1, y: 2) // true
// Hashablestruct Person: Hashable { var name: String}
// Codablestruct User: Codable { var id: Int var name: String}
// CustomStringConvertiblestruct Item: CustomStringConvertible { var description: String { "Item" }}📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”- Protocol định nghĩa contract
{ get }và{ get set }cho properties- Extension cung cấp default implementation
- Protocol composition với
& - Dùng như type cho polymorphism
- Common: Equatable, Hashable, Codable