라벨이 typeMethod인 게시물 표시

[swift] Type Method (class func vs static func)

이미지
[swift] Type Method instance vs class vs static 클래스를 사용할 때에 static이 붙은 메소드를 사용하지 못해서 문득 아 얘를 언제 쓰는지 모르고 있구나 라는 생각에 정리해 두겠습니다. func 라는 키워드는 함수를 만들 때 많이 들 보셨을 것이라고 생각합니다. 오늘은 이 앞에 붙는 키워드들의 종류와 그 이유에 대해 알아보고 정리하겠습니다. 아무것도 붙지 않음 func instanceFunc() {} class가 붙음 class func classFunc() {} static이 붙음 static func staticFunc() {} How to make Func 아무것도 붙지 않은 함수는 평범하게 아래와 같이 사용이 가능합니다. class Student { func instanceFunc(){ print("instance func leeo") } class func classFunc() { print("class func leeo") } static func staticFunc() { print("static func leeo") } } let student = Student() student.instanceFunc() Student.classFunc() Student.staticFunc() // instance func from Parents // class func from Parents // static func from Parents 그렇다면 다른 두 키워드 class , static 은 언제 쓰는 것이고 어떤 장점이 있는 걸까요? 이 두 키워드는 클래스가 만든 인스턴스에서 사용하는것이 아닌 클래스 자체에서 사용하는 메소드입니다. 이 두개를 타입 메소드라고 부르는데 어떤 의미냐 하면, 인스턴