Last active
August 29, 2015 14:17
-
-
Save hayakawatomoaki/a2fa8a830bb74d106f4e to your computer and use it in GitHub Desktop.
Swiftのシングルトンパターンでリセットもできる実装 ref: http://qiita.com/hayakawatomoaki/items/22e631dfb9ebf9e8d578
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User { | |
private struct Static { | |
static var instance: User? | |
} | |
class var sharedInstance: User { | |
if let instance = Static.instance { | |
return instance | |
} | |
Static.instance = User() | |
return Static.instance! | |
} | |
func deleteSharedInstance() { | |
Static.instance = nil | |
} | |
var i = 0 | |
func increment() { | |
i++ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class User { | |
private static var instance: User? | |
class var sharedInstance: User { | |
if let instance = instance { | |
return instance | |
} | |
instance = User() | |
return instance! | |
} | |
func deleteSharedInstance() { | |
User.instance = nil | |
} | |
var i = 0 | |
func increment() { | |
i++ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
User.sharedInstance.increment() // 1 | |
User.sharedInstance.increment() // 2 | |
User.sharedInstance.increment() // 3 | |
User.sharedInstance.increment() // 4 | |
User.sharedInstance.increment() // 5 | |
User.sharedInstance.deleteSharedInstance() | |
User.sharedInstance.increment() // 1 | |
User.sharedInstance.increment() // 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment