When would you use self in a method?
When would you use self in a method?
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:
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].
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].
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].
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào