Welcome to our deep dive into Swift programming! Today, we'll explore the difference between Structs and Classes, two fundamental building blocks of Swift. Let's get started! 📝
In Swift, both Structs (Structures) and Classes are user-defined data types, but they have distinct properties and behaviors.
Now, let's create a simple Struct and Class with properties and methods.
struct Point {
var x: Double
var y: Double
func move(x: Double, y: Double) {
self.x = x
self.y = y
}
}class Rectangle {
var width: Double
var height: Double
func area() -> Double {
return width * height
}
}There are several differences between Structs and Classes in Swift, including inheritance, default initializers, and memory management.
Let's demonstrate the differences between Structs and Classes with a practical example.
struct Point {
var x: Double
var y: Double
init(x: Double, y: Double) {
self.x = x
self.y = y
}
}
class Rectangle {
var width: Double
var height: Double
init(width: Double, height: Double) {
self.width = width
self.height = height
}
func area() -> Double {
return width * height
}
}
// Creating instances
let pointA = Point(x: 1.0, y: 2.0)
let pointB = pointA
pointB.x = 3.0
let rect1 = Rectangle(width: 5.0, height: 10.0)
let rect2 = rect1
rect2.width = 15.0
// Accessing and modifying properties
print("Point A: (pointA.x, pointA.y)")
print("Point B: (pointB.x, pointB.y)")
print("Rectangle 1: width = \(rect1.width), height = \(rect1.height), area = \(rect1.area())")
print("Rectangle 2: width = \(rect2.width), height = rect1.height, area = \(rect2.area())")In this example, we create a Struct Point and a Class Rectangle. We also create instances of each and demonstrate how modifying one instance does not affect the other.
Which of the following statements is true about Structs in Swift?
We hope you enjoyed this tutorial! In the next lesson, we'll dive deeper into the world of Swift, exploring more advanced topics. Happy coding! 🌟