如何在Swift中调用super

Sea*_*ean 13 closures ios swift

我想将一个函数链接到超级impl,如下所示

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
    })
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)

编译错误实际上清楚地告诉我原因:闭包不是类类型而且不允许.寻找任何建议如何调用超类中定义的方法?

Nat*_*ook 19

更新:从Swift 1.2 b3开始,此行为已得到修复 - 原始代码按预期工作.耶,进步!

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()
Run Code Online (Sandbox Code Playgroud)

理想情况下你可以写:

class MyClass: BaseClass {
  override func myFunc() {
    let superFunc = super.myFunc
    self.myOtherFunc(completionHandler: {
      superFunc()
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,只是打电话self.myFunc().我前几天发了推文,得到了一位Swift开发者回复,认为这是一个已知的bug.唯一的解决方法是使用另一种方法将呼叫转接到超级:

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

  func callSuperMyFunc() {
    super.myFunc()
  }
}
Run Code Online (Sandbox Code Playgroud)


rin*_*aro 5

这个答案可能无法回答你的问题..

令人惊讶的是,以下代码会导致无限递归调用.也许是个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
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

我发现的唯一解决方法是定义另一种方法:

class MyClass: BaseClass {
    override func myFunc() {
        self.myOtherFunc(completionHandler: {
            self.callSuperMyFunc()
            return
        })
    }
    func callSuperMyFunc() {
        super.myFunc()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我认为,您应该使用另一个方法名称:

class MyClass: BaseClass {
    func myFuncAsync() {
        self.myOtherFunc(completionHandler: {
            self.myFunc()
            return
        })
    }
}
Run Code Online (Sandbox Code Playgroud)