Can you rewrite this code...
Can you rewrite this code...
Certainly! Let's start by examining the provided code and then rewrite it using a mutating function.
struct Point {
var x: Double
var y: Double
func moveBy(x deltaX: Double, y deltaY: Double) -> Point {
return Point(x: x + deltaX, y: y + deltaY)
}
}
var point = Point(x: 0.0, y: 0.0)
point = point.moveBy(x: 2.5, y: 4.5)
print("Updated point: (\(point.x), \(point.y))") // Output: Updated point: (2.5, 4.5)
To rewrite this code using a mutating function, we need to modify the moveBy
method so that it directly changes the properties of the Point
instance instead of returning a new instance.
struct Point {
var x: Double
var y: Double
mutating func moveBy(x deltaX: Double, y deltaY: Double) {
x += deltaX
y += deltaY
}
}
var point = Point(x: 0.0, y: 0.0)
point.moveBy(x: 2.5, y: 4.5)
print("Updated point: (\(point.x), \(point.y))") // Output: Updated point: (2.5, 4.5)
moveBy
method returns a new Point
instance with updated coordinates, and the caller must reassign the result to the original variable.moveBy
method is marked as mutating
, allowing it to modify the properties x
and y
of the Point
instance directly. This eliminates the need to return a new instance and reassign it.By using t...
senior
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào