how to call super in closure in Swift

closures, ios, swift

Solution

Update: As of Swift 1.2 b3, this behavior is fixed—the original code works as intended. Yay, progress!

class BaseClass {
    func myFunc() {
        println("BaseClass.myFunc()")
    }
}

class MyClass: BaseClass {
    func myOtherFunc(c: () -> ()) {
        c()
    }

    override func myFunc() {
        println("MyClass.myFunc()")
        self.myOtherFunc {
            super.myFunc()
        }
    }
}

MyClass().myFunc()
// MyClass.myFunc()
// BaseClass.myFunc()

Ideally you could just write:

class MyClass: BaseClass {
  override func myFunc() {
    let superFunc = super.myFunc
    self.myOtherFunc(completionHandler: {
      superFunc()
    })
  }
}

But this doesn't work, it just calls `self.myFunc()`. I tweeted about this the other day and got a response from one of the Swift developers that it's a known bug. The only workaround is to use another method to shuttle the call to super:

class MyClass: BaseClass {
  override func myFunc() {
    self.myOtherFunc(completionHandler: {
      self.callSuperMyFunc()
    })
  }

  func callSuperMyFunc() {
    super.myFunc()
  }
}

Problem

I want to chain a func to super impl, something like the following ``` class BaseClass { func myFunc() { // do something } } class MyClass: BaseClass { override func myFunc() { self.myOtherFunc(completionHandler: { super.myFunc() // error: 'super' members cannot be referenced in a non-class type }) } ... } ``` The compilation error actually tells me the reason clearly: closure is not a class type and it is not allowed. Looking for any suggestion How do I invoke the method defined in super class?

Original source