-1

I know there isn't a direct way for implementing abstraction iOS, below is how I am doing it.

protocol ParentClass: class {
  func doSomething()
  func doSomething1()
}

class ChildClassA: ParentClass {
  func doSomething() -> Bool {

  }

  func doSomething1() -> Bool {

  }
}

class ChildClassB: ParentClass {
  func doSomething() -> Bool {

  }

  func doSomething1() -> Bool {

  }
}

How do I declare initializer in ParentClass? I want to add an initializer which will create object for ChildClassA or ChildClassB. What I basically want is: if a Flag is set, execute doSomething() from ChildClassA or execute doSomething() from ChildClassB.

tech_human
  • 6,592
  • 16
  • 65
  • 107
  • 2
    It's unclear what you're trying to achieve. You can't call subclass implementations from a superclass or a protocol though. The parent has no way of knowing about such implementing types. – Bradley Mackey Jun 08 '21 at 18:17
  • Maybe take a look at this: https://stackoverflow.com/a/50999021/6257435 – DonMag Jun 08 '21 at 18:54
  • Then my design is probably wrong. What I want to have is a class/protocol which has func stubs/declarations and the implementation of those func will be in other classes. Edit: Sorry, I was trying to add an example here, but not able to due to character limitations. Will update my question. – tech_human Jun 08 '21 at 18:55
  • "What I want to have is a class/protocol which has func stubs/declarations and the implementation of those func will be in other classes" Unclear what the protocol is for in that case. It sounds like a superclass with abstract methods that must be overridden by subclasses. See https://stackoverflow.com/questions/63831683/is-a-blank-function-conventional-in-subclass-that-conforms-to-custom-protocol/63831969#63831969 for instance. However, your talk of "declare initializer" in the question is completely at odds with anything in your code and it is thus totally unclear what the actual goal is. – matt Jun 08 '21 at 22:04
  • 1
    Also this is not at all what is usually meant by "abstraction", which makes the question even more opaque. – matt Jun 08 '21 at 22:06

1 Answers1

1

You can add a initializer requirement to a protocol as follows:

protocol ParentProtocol: class {
    init(someArgument: String)
    func doSomething()
    func doSomething1()
}

(replacing someArgument: String with whatever you need). I changed the name from ParentClass to ParentProtocol because it's not a class and that's important to understand.

This means that all classes that conform to the protocol must implement an initializer with this signature.

idz
  • 12,825
  • 1
  • 29
  • 40