Swift & runtimeHistorical technical note

Swift 3.0 Design Patterns: Singleton

Introduces the uses and trade-offs of Swift singletons, creating shared instances with a static class constant or a global constant. It covers private initializers, access across modules, and the need to consider thread safety for shared mutable state.

Original byline:Sindri

Originally credited to Sindri; edited and archived by Bison.

Source listed in the original

English translation of the Chinese original, translated on . The article body uses automated translation; app descriptions, historical reading notes and video subtitles receive separate editorial checks. Original publication dates, attribution, code and version notes are retained.

1

Editor: Bison
Source: Sindri’s Notes

Design patterns are classified, widely known, repeatedly used solutions distilled from code-design experience. The GoF proposed 23 patterns; this series implements them in Swift.

Overview

A class with exactly one instance throughout an app’s lifetime is a singleton. Sharing that object across modules is the Singleton pattern.

The Singleton pattern has these advantages:

Multiple modules share one object, keeping data unique. Centralised logic offers flexibility. iOS itself provides singletons such as NSNotificaitonCenter and UIApplication. Swift mainly uses two singleton-creation approaches. I usually store user data in a singleton for access across modules:

  • Approach 1: declare a static constant inside the class and make its initialiser private.

    class UserInfo {

        static let sharedInfo = UserInfo()

        private init() {}
    }

  • Approach 2: use a global constant object.

    let singleton = UserInfo()

        class UserInfo {
            class var sharedInfo : UserInfo {
                return singleton
            }
    }

Developers coming from Objective-C may prefer dispatch_once, but it is no longer available in Swift3.0. Apple already uses dispatch_once in static let implementation to ensure only one instance exists.

Summary

A singleton keeps data unique during the app’s lifetime and avoids duplicate memory usage, but a large singleton itself becomes a burden. Access also raises thread-safety concerns, requiring appropriate locking for stability.


Recommended reading: Implement an iOS launch-screen advertisement in minutes