Bỏ qua để đến nội dung

Struct

Struct là value type dùng để định nghĩa custom data types.

struct Person {
var name: String
var age: Int
}
var person = Person(name: "Alice", age: 25)
print(person.name) // Alice
struct Point {
var x: Double
var y: Double
// Swift tự động tạo init(x:y:)
}
let point = Point(x: 10, y: 20)
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)
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...
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())
struct Math {
static let pi = 3.14159
static func square(_ n: Double) -> Double {
return n * n
}
}
print(Math.pi)
print(Math.square(5))
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) // 100
struct Person: Codable, Hashable {
let name: String
let age: Int
}
// Codable cho JSON
let person = Person(name: "Alice", age: 25)
let data = try! JSONEncoder().encode(person)
// Hashable cho Set/Dictionary
var people: Set<Person> = [person]
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?
}

  • Struct là value type (copy on assign)
  • Memberwise initializer tự động
  • mutating cho methods thay đổi self
  • static cho type-level members
  • Phổ biến cho models, DTOs
  • Conform Codable cho JSON