Introduction
Extensions let you add new ways to create objects without changing the original code. This helps keep your code clean and organized.
extension TypeName { init(parameters) { // initialize properties } }
struct Point { var x: Double var y: Double } extension Point { init() { self.x = 0 self.y = 0 } }
class Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } } extension Rectangle { convenience init(squareSide: Double) { self.init(width: squareSide, height: squareSide) } }
struct Circle { var radius: Double } extension Circle { init() { self.radius = 1.0 } init(diameter: Double) { self.radius = diameter / 2 } } let defaultCircle = Circle() let bigCircle = Circle(diameter: 10) print("Default circle radius: \(defaultCircle.radius)") print("Big circle radius: \(bigCircle.radius)")
extension in Swift?Point via extension?init without a function keyword.init with parameters and assigns properties. Others misuse keywords like func, add extra words, or wrong keywords.init keyword only for initializers [OK]struct Rectangle {
var width: Int
var height: Int
}
extension Rectangle {
init(size: Int) {
self.width = size
self.height = size
}
}
let square = Rectangle(size: 5)
print(square.width, square.height)square with size: 5 sets width and height to 5. Printing outputs "5 5".Car?
class Car {
var model: String
init(model: String) {
self.model = model
}
}
extension Car {
init() {
model = "Unknown"
}
}model directly but does not call self.init(model:), violating the rule.User via extension that accepts a dictionary [String: String] and sets name and email. Which code correctly implements this, handling missing keys by setting empty strings??? "" provides a default empty string if the key is missing, avoiding runtime errors.self.name and self.email with safe unwrapping. extension User {
init(data: [String: String]) {
name = data["name"] ?? ""
email = data["email"] ?? ""
}
} misses self. which is required in initializers.Pass the test and this pattern moves unknown