Applying SOLID principles in Swift code is essential for writing maintainable, scalable, and testable applications. SOLID is an acronym representing five principles that guide object-oriented design:
Here is an example demonstrating these principles in Swift:
// Example demonstrating SOLID principles in Swift
protocol Shape {
func area() -> Double
}
class Rectangle: Shape {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
func area() -> Double {
return width * height
}
}
class Circle: Shape {
var radius: Double
init(radius: Double) {
self.radius = radius
}
func area() -> Double {
return Double.pi * radius * radius
}
}
class AreaCalculator {
func calculateArea(shapes: [Shape]) -> Double {
var totalArea: Double = 0
for shape in shapes {
totalArea += shape.area()
}
return totalArea
}
}
// Usage
let shapes: [Shape] = [Rectangle(width: 4, height: 5), Circle(radius: 3)]
let calculator = AreaCalculator()
let totalArea = calculator.calculateArea(shapes: shapes)
print("Total area: \(totalArea)")
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?