Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Archives
Today
Total
관리 메뉴

Jupyo's Daily Story

static, class, final class 프로퍼티/메서드 본문

Swift

static, class, final class 프로퍼티/메서드

JangJupyo 2024. 10. 26. 23:28
728x90
반응형

static

  • static은 클래스, 구조체, 열거형에서 사용 가능하며 타입 레벨 속성 또는 메서드를 정의할 때 사용
  • static으로 선언된 멤버는 서브클래스에서 오버라이드가 불가능하여 고정된 동작을 유지
class Vehicle {
    static let wheels = 4  // static 프로퍼티
    static func makeSound() {  // static 메서드
        print("Some sound")
    }
}

class Car: Vehicle {
    // static은 오버라이드 불가능
    // override static func makeSound() { } // 컴파일 에러
}

// 사용
Vehicle.wheels  // 4
Vehicle.makeSound()  // "Some sound"

 

class

  • 상속된 하위 클래스에서 오버라이드 가능
  • 오직 class에서만 사용 가능 (struct, enum에서는 사용 불가)
class Vehicle {
    class var description: String {  // class 프로퍼티
        return "운송 수단"
    }
    
    class func makeSound() {  // class 메서드
        print("Some sound")
    }
}

class Car: Vehicle {
    override class var description: String {  // 오버라이드 가능
        return "자동차"
    }
    
    override class func makeSound() {  // 오버라이드 가능
        print("부릉부릉")
    }
}

// 사용
Vehicle.description  // "운송 수단"
Car.description     // "자동차"
Car.makeSound()     // "부릉부릉"

 

final class

  • 오버라이딩을 막는 목적으로 사용
class Vehicle {
    // final class 프로퍼티
    final class var type: String {
        return "운송수단"
    }
    
    // final class 메서드
    final class func stop() {
        print("정지합니다")
    }
}

class Car: Vehicle {
    // 컴파일 에러: Cannot override property marked with final
    // override class var type: String {
    //     return "자동차"
    // }
    
    // 컴파일 에러: Cannot override method marked with final
    // override class func stop() {
    //     print("차량 정지")
    // }
}

 

주요 차이점

  오버라이드 가능 여부 사용 가능한 타입 의미론적 차이
static 불가 class, structure, enum 이 타입과 관련된 고정된 멤버
class 가능 class 이 타입과 관련되었지만 하위 클래스에서 변경될 수 있는 멤버
final class 불가 class 이 타입과 관련된, 하위 클래스에서 변경될 수 없는 멤버

 

각각 사용하면 좋은 경우

  • static
    • struct, enum을 포함한 모든 타입에서 타입 레벨 멤버가 필요할 때
    • 간단한 문법으로 오버라이드를 막고 싶을 때
  • class
    • 하위 클래스에서 다른 동작이 필요한 타입 레벨 멤버를 정의할 때
    • 템플릿 메서드 패턴 등 다형성이 필요할 때
  • final class
    • 명시적으로 오버라이드를 금지하고 싶을 때
    • 의도를 명확히 표현하고 싶을 때
반응형