[Swift]타입 메서드(Type Methods)

choe_ju·2023년 10월 11일

📖 타입 메서드(Type Methods)

  • 타입 메서드는 특정 타입 자체에 연관되어 있으며, 인스턴스화된 객체의 특정 인스턴스와는 관련이 없는 메서드입니다. 이는 특정 타입에 대해 작동하고, 타입 자체에서 호출됩니다. Swift에서 타입 메서드는 static 또는 class 키워드를 사용하여 정의됩니다.

📎 static 키워드를 사용한 타입 메서드

struct SomeStructure {
    static func someTypeMethod() {
        // 타입 메서드 구현
        print("This is a static type method")
    }
}

SomeStructure.someTypeMethod() // 타입 이름을 통해 호출
  • static 키워드를 사용하여 구조체, 열거형 및 클래스에서 타입 메서드를 정의할 수 있습니다.
  • static으로 선언된 타입 메서드는 하위 클래스에서 오버라이드할 수 없습니다.

📎 class 키워드를 사용한 타입 메서드

class SomeClass {
    class func someTypeMethod() {
        // 타입 메서드 구현
        print("This is a class type method")
    }
}

SomeClass.someTypeMethod() // 타입 이름을 통해 호출
  • class 키워드를 사용하여 클래스에서만 사용할 수 있는 타입 메서드를 정의할 수 있습니다.
  • class로 선언된 타입 메서드는 하위 클래스에서 재정의(오버라이드)할 수 있습니다.

타입 메서드를 사용하여 특정 타입과 관련된 기능을 구현할 수 있습니다. 이를 통해 특정 타입에 대한 동작을 수행하거나, 특정 타입의 속성을 조작하거나, 특정 타입과 관련된 작업을 수행할 수 있습니다.


📎 타입 메서드의 특징

  1. Self Keyword 활용: 타입 메서드 내부에서 Self 키워드를 사용하여 타입 자체를 참조할 수 있습니다. 이는 해당 메서드가 호출된 실제 타입을 참조하는 데 사용됩니다.
  2. 상속 및 다형성: class 키워드로 선언된 타입 메서드는 상속 및 재정의(오버라이드)가 가능하므로, 하위 클래스에서 재정의하여 사용할 수 있습니다.
  3. 접근 제어 및 사용: 타입 메서드 역시 기존의 접근 제어 규칙을 따릅니다. 따라서 private, internal, fileprivate, public, 또는 open과 같은 접근 제어자를 사용할 수 있습니다.

예제

class Vehicle {
    static var numberOfWheels = 0

    class func description() {
        print("This is a vehicle with \\\\(numberOfWheels) wheels.")
    }
}

class Car: Vehicle {
    override class func description() {
        numberOfWheels = 4
        super.description()
    }
}

Vehicle.description() // 출력: "This is a vehicle with 0 wheels."
Car.description()     // 출력: "This is a vehicle with 4 wheels."

위 예제에서 Vehicle 클래스는 numberOfWheels와 description()이라는 타입 메서드를 가지고 있습니다. Car 클래스는 Vehicle를 상속받아 description() 메서드를 재정의하고 numberOfWheels 값을 업데이트합니다.

타입 메서드는 객체 생성 없이 타입 자체에 대한 작업을 수행할 때 유용합니다. 이러한 메서드를 사용하여 코드를 조직화하고 관련 기능을 그룹화할 수 있습니다.

0개의 댓글