Junior — Middle
Is it possible to create an object during initialization that is considered optional by default?
sobes.tech AI
Answer from AI
Yes, in Swift, you can create an object during initialization that will be optional (i.e., not mandatory to use). To do this, simply declare the property as Optional (for example, var object: MyClass?). In the initializer, you can assign a value to this property or leave it as nil. Thus, the object is considered optional by default and can be used later if needed.
Example:
class MyClass {
var optionalObject: SomeType?
init(createObject: Bool) {
if createObject {
optionalObject = SomeType()
} else {
optionalObject = nil // object is optional
}
}
}