-
[Swift] static 함수와 class 함수! static func vs class func앱등이에게 살충제를 뿌린다./Swift 2016. 7. 20. 00:27
class func vs static func
Objective-C를 사용하면 함수를 선언할 때, 플러스(+)부호와 마이너스(-)부호를 붙여준다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters- (void)instanceMethod { [self doSomething]; } + (void)classMethod { [[SomeClass sharedInstance] doSomething]; } +부호는 클래스메소드, -부호는 인스턴스메소드.
즉, -부호를 붙인 메소드는 객체를 생성해야만 사용할 수 있고, +부호는 객체가 아닌 클래스를 통해 호출하는 메소드이다.
이와 유사한 작동이 Swift에서도 물론 제공된다.
바로 static키워드와 class키워드이다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersextension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self } 생긴건 유사해 보인다.
두 키워드의 기능에 대한 설명은 생략하고 차이점에 대해서 짚어보도록 한다.
Q. static func와 class func의 차이점은 무엇인가요?
보기엔 static은 struct, enum에서 선언할 때 사용하고 class은 클래스나 프로토콜에서 사용하는것처럼 보이는데요.. 맞나요?
자 지금부터 확인들어가것습니다잉~
A. 네, 사실입니다. 그 또한 차이점이라고 할 수 있겠습니다.
하지만 외에도 주요한 차이점들이 존재합니다. class으로 선언한 메소드들은 동적으로 dispatch되거나 서브클래스에서 override할 수 있습니다. static은 되지 않겠죠.
예제를 보도록 합시다.
이 예제에서 class타입은 override할 수 있지만, static타입은 컴파일 에러를 발생시키네요.
static타입 선언은 class final선언과 같다고 볼 수 있습니다.
'앱등이에게 살충제를 뿌린다. > Swift' 카테고리의 다른 글
[Swift] Swift로 유닛테스트를 하려면? How to Unit-test in Swift? (0) 2017.01.09 [Raywenderlich] Swift3에서 달라진 점 ( What's new in Swift3? ) (0) 2017.01.01 [Swift] String의 subString을 subscript로 구현해보자. (0) 2016.05.01 [Swift] Objective-C 오픈소스(AFNetworking 2.0)를 Swift에 적용시켜보자 (0) 2016.03.21 [Swift] 타입 캐스팅 (0) 2015.12.22