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:

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

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

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

swift Copy
class SpecialView: UIView {
    let backgroundLayer = CAShapeLayer()

    i...
middle

middle

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

senior

Is there a way to create an abstract class in Swift?

middle

Explain the defer usage in Swift

middle

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

Bình luận

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

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