How does declaring an object as a separate instance differ from using a companion object inside a class?
sobes.tech AI
Answer from AI
In Swift language, a companion object is implemented using the static or class keyword inside a class, which allows creating properties and methods associated with the class itself rather than its instances. This is analogous to the "Singleton" pattern or static members in other languages.
-
Separate instance of an object — is a specific object created using class initialization. Each instance has its own state and behavior.
-
Companion object (static object) — is a part of the class shared among all instances, and does not require creating an object to access.
Example:
class MyClass {
static let companion = MyClass()
var value: Int = 0
}
// Usage
MyClass.companion.value = 10
let instance = MyClass()
instance.value = 5
Here, companion is a static companion object accessible without creating an instance of the class, and instance is a separate instance with its own state.