如何在viewController中扩展调用函数

fred shmed

扩展中的func1无法访问viewController中的func2。有没有办法使之成为可能?

func func2() {
   // do something
}

}  //<-- View controller ends here

extension UIViewController {


func func1(){
    func2()
}
AamirR

我猜你有一个错误或错别字,你UIViewController不是在扩展ViewController,检查你的意思是这样,它可以工作:

class ViewController: UIViewController {
    func func2() {
        print("I am being called")
    }
}

extension ViewController {
    func func1(){
        func2()
    }
}

用法

let vc = ViewController()
vc.func1() // Outputs "I am being called"

示例2(的扩展名UIViewController):

extension UIViewController {
    func func1(){
        if let viewController = self as? ViewController {
            viewController.func2()
        }
    }
}

用法

let vc = ViewController()
vc.func1() // Outputs "I am being called"

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章