History
Loading...
Loading...
September 21, 2025
body clean. Instead of embedding logic directly in your view builder, create computed properties that return the processed values. This makes your views more readable and helps Xcode's preview system work more efficiently with your complex UI logic.Extract complex calculations and conditional logic into computed properties rather than embedding them directly in the view body. This separates presentation logic from view structure, making the body property focus purely on layout and composition.
struct ProductCard: View {
let product: Product
let discountPercentage: Double?
private var displayPrice: String {
if let discount = discountPercentage {
let discountedPrice = product.price * (1 - discount)
return String(format: "$%.2f", discountedPrice)
}
return String(format: "$%.2f", product.price)
}
private var priceColor: Color {
discountPercentage != nil ? .red : .primary
}
private var showOriginalPrice: Bool {
discountPercentage != nil && discountPercentage! > 0.05
}
var body: some View {
VStack(alignment: .leading) {
Text(product.name)
.font(.headline)
Text(displayPrice)
.foregroundColor(priceColor)
.font(.title2)
if showOriginalPrice {
Text(String(format: "$%.2f", product.price))
.strikethrough()
.foregroundColor(.secondary)
}
}
}
}Computed properties improve code readability, make views easier to test, reduce SwiftUI's view diffing overhead, and enable better code reuse. They also make your views more maintainable by isolating business logic from presentation structure.