2

I would like to have an initializer, that would use parameter of type that it's current class is. It's best to show by example:

class A {
    let finishBlock: @escaping (_ parameter: A) -> Void
    init(finishBlock: (_ parameter: A) -> Void) {
        self.finishBlock = finishBlock
    }
}

class B: A {}

And now I would like to have automatic init for B, in which finishBlock would use parameter: B

So something like having:

init(finishBlock: @escaping (_ parameter: Self) -> Void) {}

Is this something that is possible to achieve? I don't want to write new init for every subclass, because I'm working on a framework, which contains a base class that will be subclassed like so often, so I would like to have this kind of behavior.

Hamish
  • 78,605
  • 19
  • 187
  • 280
Damian Dudycz
  • 2,622
  • 19
  • 38
  • 1
    Currently Swift only lets you use `Self` as the return type of a class method or within a protocol – so one workaround is to use a protocol extension, see for example https://stackoverflow.com/a/42356615/2976878. However unfortunately that'll get pretty messy if you want to store the function within your class. – Hamish Mar 15 '19 at 13:24
  • 1
    The good news at least is that the implementation of [SE-0068](https://github.com/apple/swift-evolution/blob/master/proposals/0068-universal-self.md) [is currently underway](https://github.com/apple/swift/pull/22863), so hopefully this is something Swift will support in the near future (though unfortunately the implementation in the linked PR doesn't currently cover the use of `Self` in a covariant place within a function parameter, but hopefully this will be something that's iterated on). – Hamish Mar 15 '19 at 13:24

0 Answers0