안녕하세요. narvis2 입니다.
이번시간에는 Swift 문법에 중에서도 Type Method에 대하여 알아보는 시간을 가지도록 하겠습니다.
🍀 Type Method
- Type 자체에서 호출되는
Method instance를 생성하지 않고도 타입 자체에서Method를 호출할 수 있음- kotlin 의
singleton인object/companion object와 비슷
- kotlin 의
method앞에static이나class의 키워드가 붙음
| static func | class func |
|---|---|
서브 클래스에서 override 할 수 없음 | 서브 클래에서 override 가능 |
☘️ class func
class는 상속이 가능하나Struct/Enum에서는 상속이 불가능하여class func을 사용할 수 없음❗️
Struct/Enum에서는 오로지Static func만 사용 가능override가능
예제
1
2
3
4
5
6
7
8
9
class Print {
class func printMessage() {
print("Hello!!")
}
}
// Type Method로 instance를 생성해줄 필요 없이 타입 자체에서 호출할 수 있음
Print.printMessage()
☘️ static func
override불가
예제
1
2
3
4
5
6
7
8
class Print {
static func printMessage() {
print("Hello!!")
}
}
Print.printMessage()