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

When would you use self in a method?

Câu trả lời

In Swift, the self keyword is used to refer to the current instance of a class, struct, or enum within its own instance methods. Here are the primary scenarios where you would use self in a method:

1. Differentiating Between Parameters and Properties

When the names of method parameters are the same as the instance properties, self is used to distinguish between them. This is common in initializers:

struct Student {
    var name: String
    var bestFriend: String

    init(name: String, bestFriend: String) {
        self.name = name
        self.bestFriend = bestFriend
    }
}

In this example, self.name refers to the property of the instance, while name refers to the parameter passed to the initializer[7][12].

2. Within Closures

When accessing instance properties or methods from within a closure, Swift requires the use of self to make it explicit that you are capturing self and to avoid potential retain cycles:

class Person {
    var name: String
    var age: Int

    init(name: String, age: Int) {
        self.name = name
        self.age = age
    }

    var info: () -> String {
        return { [weak self] in
            guard let self = self else { return "No info" }
            return "\(self.name) is \(self.age) years old."
        }
    }
}

Here, self.name and self.age are accessed within the closure, making it clear that these are properties of the instance[1][7][12].

3. Mutating Methods in Structs

In mutating methods of structs, self can be used to assign a new value to the instance:

struct Movement {
    var speed: Int

    mutating func stop() {
        self = Movement(speed: 0)
    }
}

In this example, self is reassigned to a new instance of Movement[4].

4. Enhancing Readability and Avoiding Ambiguity

Using self can enhance code readability and avoid ambiguity, especially in complex methods where it might not be immediately clear whether a variable is a local variable or an instance property:

class SpecialView: UIView {
    let backgroundLayer = CAShapeLayer()

    i...
middle

middle

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

expert

Explain how that code will behave for different Swift versions?

middle

What's the difference between Self vs self ?

senior

What's wrong with this code?

Bình luận

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

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