[Swift] - Type Property(타입 프로퍼티)/ Type Method

longlivedrgn·2023년 1월 1일
1

swift문법

목록 보기
30/36
post-thumbnail

타입 프로퍼티(Type Property)

.타입 자체에 연결할 수 있으며, 처음 엑세스 할때는 게으르게 초기화(lazy initialized)가 됩니다.

.항상 초기화가 되어있어야한다.

.언제 한번 누군가 한번 불러서 메모리에 올라가면(그전까지는 올라가지 않는다= lazy), 그 뒤로는 생성되지 않으며 언제 어디서든 이 타입 프로퍼티에 접근 할 수 있다. ⇒ 전역변수

static, class이라는 키워드를 통하여 구현을 한다.

두 가지의 타입 프로퍼티가 존재합니다.

  • 저장 타입 프로퍼티 → var , let으로 선언 가능, 기본값을 주어야된다.
  • 연산 타입 프로퍼티 → var로만 선언이 가능

static 키워드

  • 예를 통해서 알아보자. 아래와 같이 static을 붙혀, 저장 타입 프러퍼티와 연산 타입 프러퍼티를 생성해줄 수 있다.
struct SomeStructure {

    static var storedTypeProperty = "Some value."

    static var computedTypeProperty: Int {

        return 1

    }
}

print(SomeStructure.storedTypeProperty) // "Some value."

class 키워드

"클래스 타입에 대한 연산 타입 프로퍼티(Computed type property)의 경우, "class" 키워드를 사용하여 서브클래스가 슈퍼클래스의 구현을 재정의(override)할 수 있습니다.”

  • 이 말의 뜻을 예를 통해서 알아보자!, 아래와 같이 overrideableComputedTypeProperty 연산 타입 프러퍼티를 만들어주자.
class SomeClass {

    static var storedTypeProperty = "Some value."

    static var computedTypeProperty: Int {

        return 27

    }

    class var overrideableComputedTypeProperty: Int {

        return 107

    }

}
  • 위와 같이 class를 붙혀주면, SomeClass를 상속받은 어떤 클래스에서 아래와 같이 연산 타입 프러피티를 재정의할 수 있다.
class ChildSomeClass : SomeClass{

    override static var overrideableComputedTypeProperty: Int{

        return 2222

    }

}

그렇다면 왜 쓸까?

  • 모든 타입이 공통적인 값을 정의하는 데 유용하게 쓰인다! ⇒ 싱글톤

싱글톤에 대해서 알아보고싶다면


타입 메소드(Type Method)

→ 클래스 인스턴스를 만들지 않아도 되는 타입에 붙어서 method를 바로 사용할 수 있다.

  • 예를 통해서 알아보자 → instance 생성이 아닌데도, 바로 method 사용가능
class A {
    static func isStatic() {
        print("this is static function")
    }
    
    class func isClass() {
        print("this is class function")
    }
}

A.isStatic() // "this is static function"
A.isClass() // "this is class function"

그렇다면, class와 static의 차이점은 무엇일까?

“class는 오버라이딩이 가능한데, static은 오버라이딩이 불가능하다!”


📚 출처

Swift) 프로퍼티 정복하기 (3/4) - 타입 프로퍼티(Type Property)

Swift ) Properties - Type Properties

0개의 댓글