Objective-C에 비해서 Swift에서는 Singleton Pattern을 구현하는 것이 훨씬 간편하다.
복잡(?)하게 GCD를 사용할 필요도 없고.. Java처럼 Access Modifier 만 가지고도 충분히 Singleton을 구현할 수 있다.
코드는 다음과 같다.
class Singleton { public static let shared = Singleton() private init() { // initialize code in here... } }
shared 라는 property 를 public(선언하지 않으면 internal)으로 선언하면서 동시에 static 키워드를 준다.
그리고 바로 private으로 선언된 생성자를 통해 객체를 인스턴스화 하게 되면, 우리가 원하는 형태의 Singleton을 간단하게 구현할 수 있다.