Swift

[Swift] Instance Method vs Type Method

insub4067 2022. 7. 30. 00:38

1. Instance Method는 생성된 instance가 호출하는 method 이다

 

2. type은 생성되지 않아도 해당 타입의 method 에 접근할수 있는 method 이다.

예) Playground에서 Int. 혹은 String. 하고 Type 에다가 dot를 찍고 method 를 호출해 보면 무수히 많은 method를 제안해준다

 

type method 는 함수를 선언할때 앞에 static 혹은 class 키워드를 붙이자 

static func someFunc() -> Void {
}

class func someFunction() -> Void {
}

 

그렇다면 static 과 class의 차이는 뭘까?

static은 override이 불허한다

class는 oveeride를 허용한다.

 

그렇다면 이렇게 정리할수 있다

static을 붙이면 class의 instance를 생성하지 않고 property 혹은 method에 접근할수 있다

== 말인즉슨 static func에서는 static으로 선언하지 않은 변수에 접근 할수 없다

 

왜? instance를 생성하지 않고도 호출 할수 있기 때문에 동일한 조건에 있는 static 변수만 호출 할수 있다. == static let은 생성없이 호출 할수 있다. 하지만 그냥 let은 생성해야만 호출할수 있다