적당한 고통은 희열이다

- 댄 브라운 '다빈치 코드' 중에서

Swift iOS 앱 개발/Swift

[Swift] 메서드 정복하기 Instance / static / class methods 비교

hongssup_ 2022. 5. 13. 01:43
반응형
Swift에서는 class, struct, enum 타입 내에서 정의된 함수들을 메서드라고 한다. 
호출 방식에 따라 Instance 메서드와 Type 메서드로 나뉘는데,  func 키워드로 흔히 사용하는 것이 바로 인스턴스 메서드.
인스턴스 메서드는 클래스 등의 인스턴스를 생성하여 이를 통해 메서드를 호출하고, 타입 메서드는 클래스 등의 타입으로부터 직접 메서드를 호출할 수 있다. 
타입 메서드는 오버라이딩 여부에 따라 static 또는 class 메서드로 나뉘는데, static 메서드는 오버라이딩이 불가하기 때문에 오버라이딩이 필요한 경우 class 메서드를 사용할 수도 있다. 

 

Methods 메서드란? 

일반적으로 func 으로 정의하는 것들을 함수라고 부른다. 

그 중에서도 클래스, 구조체, 열거형 타입 내에서 정의된 함수들을 메서드라고 한다. 

Objective-C에서는 클래스 내에서만 메서드 정의가 가능했지만, Swift에서는 구조체, 열거형에서도 유연하게 메서드 사용이 가능하다. 


Swift의 메서드 종류

• Instance Methods

• Type Methods

   - static methods

   - class methods

 

Instance vs Type methods

Instance methods are methods that you call on an instance of a particular type.
Type methods are methods that are called on the type itself.

인스턴스 메서드와 타입 메서드는 접근(호출) 방식에서 차이가 있다. 

class Methods {
    func instanceMethod() {
        print("instanceMethod")
    }
    static func staticMethod() {
        print("staticMethod")
    }
    class func classMethod() {
        print("classMethod")
    }
}

Instance Methods

기본적으로 흔히 사용해온 메서드가 인스턴스 메서드. 

인스턴스 메서드를 호출할 때는 인스턴스를 만들어서 사용해야 한다. 인스턴스를 먼저 생성하고 해당 인스턴스를 통해 메서드를 호출하는 방식. (인스턴스가 메모리에 할당됨)

//Instance 메서드 호출 방식
let methods = Methods()
methods.instanceMethod()

 

Type Methods

Type 메서드(static / class) 는 타입 그 자체에 바로 접근이 가능한 메서드로, 인스턴스를 메모리에 할당하지 않고 클래스 등의 타입으로부터 메서드를 직접 호출할 수 있다. 

//Type 메서드 호출 방식
Methods.classMethod()
Methods.staticMethod()

이처럼 static 과 class 메서드를 호출하기 위해서는 클래스를 굳이 인스턴스화하지 않고, 클래스로부터 직접 메서드를 호출할 수 있다.

 

static vs class methods

타입 메서드는 오버라이딩 여부에 따라 static과 class 메서드로 나뉘는데,

static 메서드는 오버라이딩 불가, class 메서드는 오버라이딩이 가능하다.

You indicate type methods by writing the static keyword before the method’s func keyword. Classes can use the class keyword instead, to allow subclasses to override the superclass’s implementation of that method.

static 키워드를 사용하여 타입 메서드를 정의할 수 있는데, override 가 불가능한 static 메서드 외에도 class 키워드를 사용하여 override가 가능한 타입 메서드를 정의해줄 수도 있다.

static func = final class func 이라고 생각해도 좋음.

구조체는 override가 불가능하기 때문에 static 메서드는 모든 타입에서 사용이 가능하지만, class 메서드는 클래스 내에서만 사용이 가능하다는 특징도 있다. 

 

static / class 메서드 사용하는 경우

공통적으로 사용되는 메서드들의 경우 helper 메서드들을 모아놓은 Utils 클래스를 따로 만들어 사용하기도 하는데,

이러한 helper 메서드들은 사용할 때마다 인스턴스를 생성하고 메모리에 할당할 필요가 없도록 static 혹은 class 메서드로 정의하여 언제 어디서든 직접 호출해서 간편하게 사용할 수 있도록 한다. 

ex) Date 형식 변환 등

class Utils {
    static func stringToDate(dateString: String) -> Date? {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
        return dateFormatter.date(from: dateString)
    }
}

 

 


참고 : Swift LanguageGuide - Methods, sun02.log, 소들이, 개발하는 정대리

728x90
반응형