Computed Properties trong Swift
1. Giới thiệu
Computed properties không lưu trữ giá trị trực tiếp, mà tính toán giá trị mỗi khi được truy cập.
2. Getter Only
struct Rectangle {
var width: Double
var height: Double
// Computed property (read-only)
var area: Double {
width * height
}
var perimeter: Double {
2 * (width + height)
}
}
let rect = Rectangle(width: 10, height: 5)
print(rect.area) // 50.0
print(rect.perimeter) // 30.03. Getter và Setter
struct Temperature {
var celsius: Double
var fahrenheit: Double {
get {
celsius * 9 / 5 + 32
}
set {
celsius = (newValue - 32) * 5 / 9
}
}
var kelvin: Double {
get { celsius + 273.15 }
set { celsius = newValue - 273.15 }
}
}
var temp = Temperature(celsius: 25)
print(temp.fahrenheit) // 77.0
temp.fahrenheit = 100
print(temp.celsius) // 37.77...4. Shorthand Setter
struct Point {
var x: Double
var y: Double
// newValue là tên mặc định
var magnitude: Double {
get {
sqrt(x * x + y * y)
}
set {
let ratio = newValue / magnitude
x *= ratio
y *= ratio
}
}
}5. Read-Only Shorthand
struct Circle {
var radius: Double
// Có thể bỏ get khi read-only
var diameter: Double { radius * 2 }
var circumference: Double { 2 * .pi * radius }
var area: Double { .pi * radius * radius }
}
let circle = Circle(radius: 5)
print(circle.area) // 78.53...6. Trong Class và Enum
class Person {
var firstName: String
var lastName: String
var fullName: String {
get { "\(firstName) \(lastName)" }
set {
let parts = newValue.split(separator: " ")
firstName = String(parts.first ?? "")
lastName = String(parts.last ?? "")
}
}
init(firstName: String, lastName: String) {
self.firstName = firstName
self.lastName = lastName
}
}
enum Direction {
case north, south, east, west
var opposite: Direction {
switch self {
case .north: return .south
case .south: return .north
case .east: return .west
case .west: return .east
}
}
}7. Lazy vs Computed
struct DataManager {
// Lazy: tính một lần, lưu kết quả
lazy var expensiveData: [Int] = {
print("Loading data...")
return Array(1...1000000)
}()
// Computed: tính mỗi lần truy cập
var currentTime: Date {
Date()
}
}8. Sử dụng thực tế
struct User {
var firstName: String
var lastName: String
var email: String
var isValidEmail: Bool {
email.contains("@") && email.contains(".")
}
var displayName: String {
"\(firstName) \(lastName.prefix(1))."
}
}
struct Cart {
var items: [CartItem]
var subtotal: Double {
items.reduce(0) { $0 + $1.price * Double($1.quantity) }
}
var tax: Double { subtotal * 0.1 }
var total: Double { subtotal + tax }
var itemCount: Int { items.reduce(0) { $0 + $1.quantity } }
}📝 Tóm tắt
- Computed properties tính giá trị mỗi lần truy cập
getđể đọc,setđể ghinewValuelà giá trị mới trong setter- Read-only có thể bỏ
get { } - Dùng cho derived data, validation, formatting
Last updated on
Swift