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.
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" }
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.