Struct
1. Giới thiệu
Phần tiêu đề “1. Giới thiệu”Struct là value type dùng để định nghĩa custom data types.
2. Khai báo Struct
Phần tiêu đề “2. Khai báo Struct”struct Person { var name: String var age: Int}
var person = Person(name: "Alice", age: 25)print(person.name) // Alice3. Memberwise Initializer
Phần tiêu đề “3. Memberwise Initializer”struct Point { var x: Double var y: Double // Swift tự động tạo init(x:y:)}
let point = Point(x: 10, y: 20)4. Custom Initializer
Phần tiêu đề “4. Custom Initializer”struct Rectangle { var width: Double var height: Double
init(width: Double, height: Double) { self.width = width self.height = height }
init(side: Double) { self.width = side self.height = side }}
let rect = Rectangle(width: 10, height: 20)let square = Rectangle(side: 5)5. Computed Properties
Phần tiêu đề “5. Computed Properties”struct Circle { var radius: Double
var area: Double { return .pi * radius * radius }
var circumference: Double { return 2 * .pi * radius }}
let circle = Circle(radius: 5)print(circle.area) // 78.54...6. Methods
Phần tiêu đề “6. Methods”struct Counter { var count = 0
mutating func increment() { count += 1 }
mutating func reset() { count = 0 }
func describe() -> String { return "Count is \(count)" }}
var counter = Counter()counter.increment()print(counter.describe())7. Static Properties và Methods
Phần tiêu đề “7. Static Properties và Methods”struct Math { static let pi = 3.14159
static func square(_ n: Double) -> Double { return n * n }}
print(Math.pi)print(Math.square(5))8. Value Type Semantics
Phần tiêu đề “8. Value Type Semantics”struct Point { var x: Int var y: Int}
var point1 = Point(x: 10, y: 20)var point2 = point1 // Copy được tạo
point2.x = 100
print(point1.x) // 10 (không thay đổi)print(point2.x) // 1009. Conform to Protocols
Phần tiêu đề “9. Conform to Protocols”struct Person: Codable, Hashable { let name: String let age: Int}
// Codable cho JSONlet person = Person(name: "Alice", age: 25)let data = try! JSONEncoder().encode(person)
// Hashable cho Set/Dictionaryvar people: Set<Person> = [person]10. Ví dụ thực tế
Phần tiêu đề “10. Ví dụ thực tế”struct User: Codable { let id: Int let name: String let email: String
var displayName: String { name.isEmpty ? "Unknown" : name }
func validate() -> Bool { return !name.isEmpty && email.contains("@") }}
struct APIResponse<T: Codable>: Codable { let status: Int let data: T? let message: String?}📝 Tóm tắt
Phần tiêu đề “📝 Tóm tắt”- Struct là value type (copy on assign)
- Memberwise initializer tự động
mutatingcho methods thay đổi selfstaticcho type-level members- Phổ biến cho models, DTOs
- Conform Codable cho JSON