* Create Singletons

* Update README.md

* Fix singleton name

* PR feedback
This commit is contained in:
Dale 2022-02-18 09:54:31 +00:00 коммит произвёл GitHub
Родитель 9e7604c851
Коммит a816404263
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 40 добавлений и 0 удалений

Просмотреть файл

@ -16,6 +16,7 @@ The Swift coding conventions guide documents many best practices for writing Swi
* [Naming](Naming.md)
* [Property Observers](PropertyObservers.md)
* [Range Operators](RangeOperators.md)
* [Singletons](Singletons.md)
* [Type Casting](TypeCasting.md)
* [Type Inference](TypeInference.md)

39
Singletons.md Normal file
Просмотреть файл

@ -0,0 +1,39 @@
# Singletons
## Convention
If a singleton must be used (and effort should be taken to avoid this where possible), then they should always be implemented as a class with a shared reference to an instance of itself, with instance properties, rather than static properties.
## Rationale
Following this convention makes it clear that this class is a singleton and should be used that way. More importantly, it makes testing significantly simpler as new versions can be instatiated and passed around.
## Examples
```swift
// good: The singleton has no static properties
class MyManager {
static let shared = MyManager()
var someVar: String = "Hello"
}
// bad: The singleton only has static properties
class MyManager {
static var someVar: String = "Hello"
}
// A more complete example
public class OurDefaults {
// Called throughout the application
public static let shared = OurDefaults(userDefaults: .standard)
private let userDefaults: UserDefaults
// Called during test case set up
// Initializer also makes it clear how many dependencies this class has.
init(userDefaults: UserDefaults) {
self.userDefaults = userDefaults
}
}
```