how to call super in closure in Swift
This answer might not answering your question..
Surprisingly, the following code causes infinite recursive call. Maybe a bug?
class MyClass: BaseClass {
override func myFunc() {
let superMyFunc = super.myFunc
self.myOtherFunc(completionHandler: {
superMyFunc() // this actually calls MyClass.myFunc
return
})
}
}
// ALSO
class MyClass: BaseClass {
override func myFunc() {
let superMyFunc = BaseClass.myFunc(self as BaseClass)
self.myOtherFunc(completionHandler: {
superMyFunc() // this actually calls MyClass.myFunc
return
})
}
}
The only workaround I found out is defining another method:
class MyClass: BaseClass {
override func myFunc() {
self.myOtherFunc(completionHandler: {
self.callSuperMyFunc()
return
})
}
func callSuperMyFunc() {
super.myFunc()
}
}
But, I think, you should use another method name:
class MyClass: BaseClass {
func myFuncAsync() {
self.myOtherFunc(completionHandler: {
self.myFunc()
return
})
}
}
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()
}
}