Câu hỏi phỏng vấn Swift
Câu hỏi

Can you rewrite this code...

Câu trả lời

Certainly! Let's start by examining the provided code and then rewrite it using a mutating function.

Original Code

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)

Rewritten Code Using Mutating Function

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)

Explanation

  • Original Code: The moveBy method returns a new Point instance with updated coordinates, and the caller must reassign the result to the original variable.
  • Rewritten Code: The 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

senior

Gợi ý câu hỏi phỏng vấn

middle

What does the required keyword in Swift mean?

middle

When to use a set rather than an array in Swift?

expert

What’s the difference between init?() and init() ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào