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

What does the Swift mutating keyword mean?

Câu trả lời

The mutating keyword in Swift is used to indicate that a method can modify the properties of a value type, such as a struct or an enum. By default, methods on value types cannot change the instance's properties. The mutating keyword explicitly allows the method to alter the instance's state.

Key Points about mutating Keyword:

  1. Value Types: In Swift, structs and enums are value types, meaning they are copied when assigned to a new variable or passed to a function. This immutability by default ensures that the original instance remains unchanged unless explicitly allowed to mutate.

  2. Method Declaration: When you define a method within a struct or enum that modifies any of its properties, you must prefix the method with the mutating keyword. This informs the compiler and the caller that the method will change the instance's state.

  3. Usage Example:

    swift Copy
    struct Person {
        var name: String
        
        mutating func changeName(to newName: String) {
            name = newName
        }
    }
    
    var person = Person(name: "Alice")
    person.changeName(to: "Bob")
    print(person.name) // Outputs: Bob
  4. Reassigning self: Within a mutating method, you can also reassign self to a new instance, effectively replacing the entire instance with a new one.

    swift Copy
    struct Point {
        var x: Int
        var y: Int
        
        mutating func moveTo(x newX: Int, y newY: Int) {
            self = Point(x: newX, y: newY)
        }
    }
  5. Protocols: When a protocol requires a method that modifies the instance, the method must be marked as mutating in the protocol definition. Classes conforming to such protocols do not need to use the mutating keyword because classes are reference types and inherently mutable.

    swift Copy
    protocol Resettable {
        mutating func reset()
    }
    
    struct Counter: Resettable {
        var count: Int = 0
        
        mutating func reset() {
            count = 0
        }
    }
  6. Constants and Variables: You cannot call a mutating method on a constant instance of a struct or enum. The instance must be a variable.

    swift Copy
    let fixedPoint = Point(x: 0, y: 0)
    // fixedPoint.moveTo(x: 10, y: 10) ...
middle

middle

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

middle

What is the difference between let and var in Swift?

middle

How to sort array of custom objects by property value in Swift?

senior

Explain when to use different Swift casting operators?

Bình luận

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

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