IOS application/Swift

6. Instance Method vs. Type Method

개발자킹콩 2021. 4. 22. 21:12

Instance Method vs. Type Method

 

https://cocoacasts.com/swift-fundamentals-what-is-the-difference-between-instance-methods-and-type-methods-in-swift

 

What Is the Difference Between Instance Methods and Type Methods in Swift

Before I can explain the difference between instance methods and type methods, you first need to understand what an instance is and what a type is. Let me show you an example. Fire up Xcode and create a playground. Remove the contents of the playground and

cocoacasts.com

 

 

 

 


 

 

 

Instance method와 type method의 차이는 무엇일까?

이를 이해하기 위해서는 우선 인스턴스와 타입에 대해 이해 해야한다. 

 

 

 

 

User 이라는 struct를 선언하고 String type을 갖는 name property를 선언한다.

여기서 User은 type이다. 새로운 type를 정의한 것이다.

 

 

우리는 위의 코드와 같이 User의 memberwise initializer을 호출해서 User을 생성할 수 있다.

현재 생성된 jane는 instance이다. 

 

User 은 type이고, jane는 instance이다. (클래스와 객체의 차이점인가?)

 

type와 instance의 차이점을 이해했으면 이미 이해한거나 다름없다.

우리는 여기서 method를 정의해보자. 

 

 

 

 


 

 

 

 

Instance Method

 

 

(여기서 오타가 발생했는데 greeting를 sayHello라고 생각하자.)

현재 정의된 sayHello는 instance method이다. 

왜? 이 method를 실행시키려면 instance가 있어야 하기때문이다.

실체가 있어야 사용할 수 있는 method이기에 instance method라고 한다.

 

 

 

실제 코드 작성시 User.sayHello()는 실체가 없는 상태에서 함수를 호출하는 것이다.

Class, struct, type, 설계도  <—>  object, instance, 물건

 

아파트 설계도만 만들어진 상태에서 집들어가기() 기능은 사용할 수 없다는 의미이다.

실체인 instance를 생성해야, 아파트를 실체로 설계도에 의해 만들어 져야 비로소 집들어가기() 기능을 수행할 수 있다는 말이다.

 

 

 

 

 


 

 

 

 

 

Type method

 

그렇다면 type method는 무엇일까? static으로 선언된 것이 type method이다. 

 

 

 

 

 

 

static으로 선언된 type method는 언제 사용하는 것인가?

 

 

 

위와 같이 생성하고 싶을때 사용하는 것이다.

실제 인스턴스에서 type method를 호출하면 에러가 발생한다. 

Type method는 type에서 호출해야 한다.

 

 

instance없이 생성하는 이유 혹은 장점은 무엇인가?

이것은 새로운 기능을 제공하는 것이다.

좋은 예시인지는 모르겠지만 하나 들어보자면,

우리가 현재 설계도만 있는 아파트가 있을때, 사고 파는 기능이 필요할 수 있다.

생각보다 일생생활에서는 이러한 일이 다양하다. 나는 이렇게 예시를 생각했다.

 

 

 

 

 


 

 

 

 

 

Class Method?

 

Static 키워드는 type method를 생성할 수 있는 유일한 옵션은 아니다. --> Class keyword

 

 

다음과 같이 static와 class 키워드를 사용해서 type method를 만들 수 있다.

 

 

 

 

그렇다면 차이는 무엇일까? 하위 클래스를 만들면 차이점이 확연히 보인다.

 

 

우리가 static method를 subclass에서 override하면 에러가 발생한다. 

 

 

 

 

Static method 가 정의되어 있는 class의 subclass에서는 상위에서 선언된 static method를 override할 수 없다는 것이다. —> Enum과 struct는 상속을 지원하지 않기 때문이다.

 

static를 사용할꺼면 enum과 struct에서 사용하고 static type method가 선언된 클래스의 하위클래스에서는 override를 지원하지 않는다는 점을 주의하자. 

사용할꺼면 static type method가 아닌 class type method를 선언해서 override를 해야한다.

 

 

 

 

 

 

 

 

 

'IOS application > Swift' 카테고리의 다른 글

8. Tabbar, SafeArea, collectionView 설정  (0) 2021.04.24
7. Swift Escaping Closure ?? 😁  (0) 2021.04.23
5. AVMetadataItem  (0) 2021.02.18
4. Design Patton: MVVM 패턴  (0) 2021.02.06
3. 상속은 언제 하면 좋은가?  (0) 2021.01.22