Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call super in closure in Swift

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?

like image 555
Sean Avatar asked Nov 26 '14 05:11

Sean


1 Answers

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()
  }
}
like image 118
Nate Cook Avatar answered Oct 12 '22 14:10

Nate Cook