I'm looking for the right way of unwrapping optional to an instance variable in swift.
I have a singleton class, shared
property of which can be nil, and I'm trying to assign the instance of the singleton in the failable initializer of another class so that I can use the singleton instance without caring of unwrapping it every time.
It looks like this:
class A {
static let shared = A()
let b = 1
private init?() {
return nil
}
}
class B {
let a: A
init?() {
if A.shared != nil {
a = A.shared!
} else {
return nil
}
print(a.b)
}
}
B()
Is there any way of doing this in a shorter way (using guard
, if
, etc.)?
You can write the init?
of B
as follows:
init?() {
guard let a = A.shared else { return nil }
self.a = a
print(a.b)
}
It's best to avoid code in the pattern:
if someVar != nil {
x = someVar!
}
guard let
or if let
exist to avoid such constructs.
But there is no way to avoid dealing with your optional singleton other than not making it optional. It's unusual to have an optional singleton instance.