0%

swift 中如何使用带参数的单例

前言

swift 中如何使用带参数的单例

步骤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
private class SingletonSetupHelper {
var param:String?
}

class MySingleton {
static let shared = MySingleton()
private static let setup = SingletonSetupHelper()

class func setup(param:String){
MySingleton.setup.param = param
}

private init() {
let param = MySingleton.setup.param
guard param != nil else {
fatalError("Error - you must call setup before accessing MySingleton.shared")
}

//Regular initialisation using param
}
}

初始化单例的时候要先设置 SingletonSetupHelper 否则会出现 fatalError

1
MySingleton.setup(param:"MyParam")

正常使用单例

1
MySingleton.shared()

参考

https://stackoverflow.com/a/40464136/4256995