Swift - self / Self

이한솔·2024년 4월 8일
0

Swift 문법 🍎

목록 보기
30/32

self / Self의 차이

combine을 공부하다가 모르는 키워드를 발견했다. Self란 무엇인가?

public func receive<S>(subscriber: S) where S: Subscriber, Self.Failure == S.Failure, Self.Output == S.Input {
    let subscription = Subscription(subscriber: subscriber, input: output, event: event)
    subscriber.receive(subscription: subscription)
}


self

self는 소문자로 시작하는 키워드로, 현재 인스턴스를 나타낸다. 주로 메서드 내에서 사용되며, 해당 메서드를 호출한 현재 인스턴스를 가리킨다. self를 사용하여 인스턴스의 속성에 접근하거나, 메서드를 호출하거나, 인스턴스 자체를 전달할 수 있다.

class Person {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func printName() {
        print("My name is \(self.name)")
    }
    
    func changeName(newName: String) {
        self.name = newName
        self.printName() // 다른 메서드 호출 시에도 self 사용 가능
    }
}

let person1 = Person(name: "Alice")
person1.printName() // My name is Alice

person1.changeName(newName: "Bob") // My name is Bob
print(person1.name) // Bob


Self

Self는 주로 프로토콜과 관련된 타입에서 사용된다. Self를 사용하면 현재 타입의 실제 타입을 참조할 수 있다. 이를 통해 프로토콜을 채택한 여러 클래스 또는 구조체에서 해당 프로토콜을 구현할 때 유용하게 사용된다.

protocol Animal {
    static var type: String { get }
    func makeSound()
}

extension Animal {
    static func printType() {
        print("Type: \(Self.type)")
    }
}

class Dog: Animal {
    static var type: String { return "Dog" }
    
    func makeSound() {
        print("Woof!")
    }
}

class Cat: Animal {
    static var type: String { return "Cat" }
    
    func makeSound() {
        print("Meow!")
    }
}

let dog = Dog()
dog.makeSound() // Woof!
Dog.printType() // Type: Dog

let cat = Cat()
cat.makeSound() // Meow!
Cat.printType() // Type: Cat

이렇게 Self를 사용하면 프로토콜과 관련된 타입에서 현재 타입을 참조할 수 있다. 프로토콜의 요구사항을 구현하는 여러 클래스나 구조체에서 특정 프로퍼티나 메서드를 공통적으로 사용할 때 유용하다.

0개의 댓글