OGeek|极客世界-中国程序员成长平台

标题: ios - View Controller 中的依赖注入(inject) [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 20:34
标题: ios - View Controller 中的依赖注入(inject)

谁能解释一下 View Controller 中的依赖注入(inject),我们如何摆脱可选项?我已经阅读了很多关于它的文章,但并不清楚它。将数据从一个 VC 传递到另一个 VC 是否是一种好方法?

class SecondVC: UIViewController {
    var number: [String]?

    override func viewDidLoad() {
        super.viewDidLoad()

        self.printNumbers()
    }

    func printNumbers() {
        guard let number = self.number else { return }

        print(number)
    }
}

//+++++++ In First View Controller +++++++++++++++++

@IBAction func pushToSecondVC(_ sender: UIButton) {
    let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("SecondVC") as SecondVC
    secondViewController.number = self.numbers
    self.navigationController.pushViewController(secondViewController, animated: true)
}



Best Answer-推荐答案


在您的示例中,如果您只是想摆脱可选项,请将您的 var number: [String]? 替换为 var number = [String]()。这将创建一个空数组。

当您必须访问此属性时,您不再需要打开它。

关于ios - View Controller 中的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52259854/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4