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:

    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.

    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.

    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.

    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's the difference between Self vs self ?

junior

What are Extensions used for in Swift?

senior

Explain the difference between weak and unowned references. Provide an example

Bình luận

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

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