2

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!

Community
  • 1
  • 1
Alex Bardasu
  • 348
  • 1
  • 8

1 Answers1

2

If I understood the question correctly, this should work:

class B {
    var a: Type1

    init(a: Type1) {
        self.a = a
    }
}

class A : B {
    var b: Type2

    init(a: Type1, b: Type2) {
        self.b = b
        super.init(a: a)
    }
}
Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
  • This would work, but the problem is I have to have B's init as required (I'm not allowed to change it). – Alex Bardasu Dec 14 '14 at 23:22
  • OH, I see. Well, the docs says: "Write the required modifier before the definition of a class initializer to indicate that every subclass of the class must implement that initializer" I would say, you must implement that initializer. However, it says also: "You do not have to provide an explicit implementation of a required initializer if you can satisfy the requirement with an inherited initializer. " So maybe if you have an inhereted initializer in class B, then you don't need the required. Otherwise, I would be interested as well. – Dániel Nagy Dec 15 '14 at 08:59