I read that creating a struct or global constant was required to implement the singleton pattern in Swift as "Swift doesn't support type stored properties"
final class BackupServer {
let name:String;
private var data = [DataItem]();
private init(name:String) {
self.name = name;
globalLogger.log("Created new server \(name)");
}
func backup(item:DataItem) {
data.append(item);
globalLogger.log("\(name) backed up item of type \(item.type.rawValue)");
}
func getData() -> [DataItem]{
return data;
}
class var server:BackupServer {
struct SingletonWrapper {
static let singleton = BackupServer(name:"MainServer");
}
return SingletonWrapper.singleton;
}
}
Is this still true in Swift2? I am learning how to implement the Singleton pattern in Swift for my own interest and don't need to be told it is an anti-pattern. The docs seem to say that stored type properties are possible
The best way I've seen to create a singleton in Swift is the following:
class SingletonClass {
static let sharedInstance = SingletonClass()
private init() {} //This prevents others from using the default '()' initializer for this class.
}
You can read the full explanation here: http://krakendev.io/blog/the-right-way-to-write-a-singleton
Elsewhere in the docs there is a section on singletons which I had not seen:
In Swift, you can simply use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:
class Singleton {
static let sharedInstance = Singleton()
}
If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:
class Singleton {
static let sharedInstance: Singleton = {
let instance = Singleton()
// setup code
return instance
}()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.