안녕하세요. 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()