Here's the scenario. I have three classes: A
, B
, and C
. Class A
is a subclass of B
. Class C
needs to pass one of its instance variables to class A
(let's call it b
). I want to make sure that it happens when C
initializes A
to make sure that I won't run into any situations where b
is nil. Here's how A
and B
are structured:
class B {
var a: Type1
required init(a: Type) {
...
}
}
class A : B {
var b: Type2
...
}
Swift rules dictate that a variable that is not optional or implicitly unwrapped must be defined at initialization time. However, since I have to implement B's init (I have no control over B; given by Apple) I cannot guarantee that, as I cannot add an extra parameter to A's initializer.
I want to make sure that A is called with A(b)
or A(a,b)
, but not A(a)
, to make sure that b is initialized. I tried searching for a solution or thinking about a solution using protocols or extensions, but I couldn't figure it out. The closes I've got to an answer is through this answer, but it doesn't really do what I want.
So I have two questions (one invalidates the other): 1. [The obvious one] Is there a solution to this? (Am I missing something really obvious?) 2. Am I approaching this wrong? Is there a different pattern I should be using?
Thanks!