LoginSignup
6
5

More than 3 years have passed since last update.

Swift ジェネリッククラスでシングルトンを実現する

Last updated at Posted at 2019-07-19

Swiftでシングルトンを実現する場合、以下のようになりますが

class foo {
    static let shared = foo()
    private init(){}
}

ジェネリッククラスにするとエラーになってしまいます。

class foo<T> {
    static let shared = foo<T>() // Static stored properties not supported in generic types
    private init(){}
}

コンピューテッドプロパティにすれば回避できますが、アクセスする度にインスタンスを生成してしまいます。インスタンスはできるかぎり再利用したいです。

class foo<T> {
    static var shared: foo<T> {
        return foo<T>()
    }
    private init(){}
}

インスタンスを保持しようとしても、上記と同じエラーになってしまいます。

class foo<T> {
    private static var instances: [String: AnyObject] = [:] // Static stored properties not supported in generic types

    static var shared: foo<T> {
        let type = String(describing: T.self)

        if let instance = instances[type] as? foo<T> {
            return instance
        }

        let instance = foo<T>()
        instances[type] = instance
        return instance
    }

    private init() { }
}

そこで、いささか不格好ですがグローバル空間にインスタンスを保存する作戦に至りました。さいわいにもSwiftはfileprivateという便利なアクセスレベルがあるので、グローバル空間もそこまで汚れません。

fileprivate var instances: [String: AnyObject] = [:]

class foo<T> {
    static var shared: foo<T> {
        let type = String(describing: T.self)

        if let instance = instances[type] as? foo<T> {
            return instance
        }

        let instance = foo<T>()
        instances[type] = instance
        return instance
    }

    private init() { }
}

もっとイケてる方法がありましたら教えてください。

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5