iOS/Swift 상식

Instance Method, Type Method

HJ39 2023. 2. 4. 20:49

Instance Method

인스턴스 메서드는 특정 클래스, 구조체, 열거형 인스턴스에 속한 메서드를 의미한다.

흔히 우리가 알고 있는 함수들을 의미한다.

 

Instance Method인 thisIsInstanceMethod를 접근해 보자

class JJ{
	func thisIsInstanceMethod(){
    	print("hello")
    }
}



let jj: JJ = .init()
jj.thisIsInstanceMethod()

해당 인스턴스 메서드에 접근하려면 클래스 JJ를 인스턴스를 생성하고 생성된 JJ인스턴스에.(dot)을 통해 접근할 수 있다.

 

 

Class Method를 알아보기 전에 Type Method를 먼저 알아보자

Type Method

Type Method란 Class Method와 Static Method를 묶어서 부르는 말이다.

Type Method의 내부 Method에 접근하기 위해서는 Instance를 생성할 필요 없이 클래스 이름으로 직접적으로 접근이 가능하다.

 

class JJ{
    static func thisIsStaticMethod(){
    	print("thisIsStaticMethod")
    }
    
    class func thisIsClassMethod(){
        print("thisIsClassMethod")
    }
}

let staticMethod = JJ.thisIsStaticMethod()
let classMethod = JJ.thisIsClassMethod()

위 예제만 봐서는 static Method와 Class Method의 차이점을 알 수 없다.

 

두 메서드의 차이점은 상속을 통해 알아볼 수 있다.

class jj: JJ{
    override static func thisIsStaticMethod(){ }	//Error 발생
    
    override class func thisIsClassMethod(){ }
}

위 예제를 상속받는 jj 클래스라고 하는 경우 static Method는 오버라이딩이 불가능하지만 class Method는 오버라이딩이 가능하다.

Class Method의 경우 말 그대로 class 이므로 struct, enum에서 사용할 수 없다. (struct, enum은 상속이 안되기 때문!)

 

간단하죠..?

 

 

정리하자면 

Instance Method

Class, Struct, Enum을 인스턴스화하여 사용한다.

Static Method

Class, Struct, Enum에서 사용할 수 있지만 Class에서 사용하는 경우 오버라이딩은 할 수 없다.

인스턴스화할 필요 없이 직접적으로 접근이 가능하다.

Class Method

Class에서만 사용할 수 있고 오버라이딩하여 사용할 수 있다.

인스턴스화할 필요 없이 직접적으로 접근이 가능하다.

 

 

 

# 참고한 사이트

  1. https://babbab2.tistory.com/122
  2. https://velog.io/@hayeon/instance-%EB% A9%94% EC%84% 9C% EB%93% 9C% EC%99%80-class-%EB% A9%94% EC%84% 9C% EB%93% 9C% EC% 9D%98-%EC% B0% A8% EC% 9D% B4% EC% A0%90% EC% 9D%84-%EC%84% A4% EB% AA%85% ED%95%98% EC% 8B% 9C% EC%98% A4

'iOS > Swift 상식' 카테고리의 다른 글

Singleton 패턴 알아보기  (0) 2023.02.05
Delegate 패턴 알아보기  (0) 2023.02.04
Swift - String의 SubScript 접근  (0) 2023.01.23
Swift - Optional  (0) 2023.01.23
Swift - Any vs AnyObject  (0) 2023.01.23