Welcome to the Default Initializers tutorial! In this lesson, we'll explore how to create and understand default initializers in Swift š”. By the end of this tutorial, you'll be able to write clean, effective code using default initializers in your Swift projects.
Default initializers are special methods that Swift provides for you automatically. They are used to initialize the properties of a class, structure, or enumeration with default values. This makes it easier for you to create instances of these types with minimal setup.
Let's dive into an example for each type!
class Car {
var make: String
var model: String
var year: Int
// Default Initializer
init() {
self.make = "Toyota"
self.model = "Corolla"
self.year = 2020
}
}In this example, we've created a Car class with three properties: make, model, and year. We've also defined a default initializer that sets default values for these properties.
š” Pro Tip: To create an instance of this class, you can simply call the default initializer:
let myCar = Car()struct Dimensions {
var width: Double
var height: Double
var length: Double
}
// Default Initializer
struct Point {
var x: Double
var y: Double
var dimensions: Dimensions
init() {
self.x = 0.0
self.y = 0.0
self.dimensions = Dimensions(width: 1.0, height: 1.0, length: 1.0)
}
}In this example, we've defined a Point structure with three properties: x, y, and dimensions. The dimensions property is a nested Dimensions structure. We've also defined a default initializer that sets default values for the x, y, and dimensions properties.
enum Direction {
case north, south, east, west
// Default Initializer
init() {
self = .north
}
}In this example, we've defined an Enumeration (Direction) with four cases: north, south, east, and west. We've also defined a default initializer that sets the default case to north.
That's all for the Default Initializers tutorial! As you continue to learn and practice, you'll gain more confidence in using default initializers in your Swift projects. Happy coding! š¤š