Swift singleton pattern is not documented
| Originator: | brent | ||
| Number: | rdar://17497986 | Date Originated: | 28-Jun-2014 09:59 PM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode6-Beta2 (6A216f) |
| Classification: | Feature (New) | Reproducible: | Always |
Summary:
Discussion on the developer forums indicated that the recommended singleton pattern in Swift is to simply declare a class constant, and, if the object might be encoded using NSCoding, use awakeAfterUsingCoder to replace it:
class Foo {
class let sharedFoo = Foo() // once class vars are supported; there are getter-based workarounds too
func awakeAfterUsingCoder(aDecoder: NSCoder!) -> AnyObject! {
return Foo.sharedFoo
}
}
This pattern is not discussed in any documentation. I believe it should be.
Steps to Reproduce:
1. Search “The Swift Programming Language” for the word “singleton”.
Expected Results:
A section discussing how singletons should be implemented in Swift, and how this pattern may or may not differ from Objective-C’s techniques.
Actual Results:
No such section is included.
Notes:
I’m not a huge fan of allowing multiple instances of a singleton to be allocated in any way, but the pattern mentioned above is at least acceptable. However, it’s not an obvious thing to do, and it’d be helpful if the documentation pointed it out.
Comments
Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!