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

swift Copy
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.

swift Copy
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

When would you use self in a method?

expert

Why can not we just use weak everywhere and forget about unowned ?

expert

What is the difference between @escaping and @nonescaping Closures in Swift?

Bình luận

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

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