프로퍼티에 인스턴스 프로퍼티와 타입 프로퍼티가 있는 것처럼,
메서드에도 인스턴스 메서드와 타입 메서드가 있다.
이번에 알아볼 타입 메서드는 타입 자체에서 호출이 가능하다. 객체지향 프로그래밍에서의 클래스 메서드와 유사하다.
타입 프로퍼티를 만들 때 앞에 static 키워드를 붙인 것처럼, 이번에는 메서드앞에 static 키워드를 사용하여 타입 메서드임을 나타내 줄 수 있다.
static 키워드와 class 키워드를 사용하여 타입 메서드를 만드는 두가지 방법이 있다.
static 키워드로 메서드를 정의하면 상속 후 메서드 재정의가 불가능하며
class 키워드로 메서드를 정의하면 상속 후 메서드 재정의가 가능하다.
class AClass {
//static 타입 메서드
static func staticTypeMethod() {
print("AClass staticTypeMethod")
}
//class 타입메서드
class func classTypeMethod() {
print("AClass classTypeMethod")
}
}
class BClass: AClass {
/* 재정의 불가!
override static func staticTypeMethod() {
}
*/
override static func classTypeMethod() {
print("BClass clasTypeMethod")
}
}
AClass.staticTypeMethod() //AClass staticTypeMethod
AClass.classTypeMethod() //AClass classTypeMethod
BClass.classTypeMethod() //BClass clasTypeMethod
또한 타입메서드 에서의 self 프로퍼티는 타입 그자체를 가리킨다는 점을 주의하자. 그래서 타입 메서드에서 self 프로퍼티를 사용하면 타입 프로퍼티, 타입 메서드를 호출할 수 있다.
'Swift' 카테고리의 다른 글
Swift: 접근제어의 필요성 (0) | 2022.02.14 |
---|---|
Swift: 인스턴스 생성1 (0) | 2022.02.12 |
Swift: 인스턴스 메서드(Instance Method) (0) | 2022.02.11 |
Swift: 키 경로(Key Path) (0) | 2022.02.11 |
Swift: 타입 프로퍼티(Type Property) (0) | 2022.02.06 |