【问题标题】:Cannot use optional chaining on non-optional value of type 'ViewController'不能对“ViewController”类型的非可选值使用可选链接
【发布时间】:2021-05-06 09:36:01
【问题描述】:

我对 swift 完全陌生,并且遵循有关创建待办事项列表应用程序的教程。只要我在self.createItem(name: text 中添加问号,就会收到错误Cannot use optional chaining on non-optional value of type 'ViewController'

@objc private func didTapAdd() {
        let alert = UIAlertController(title: "New Item", message: "Enter new Item", preferredStyle: .alert)
        alert.addTextField(configurationHandler: nil)
        alert.addAction(UIAlertAction(title: "Submit", style: .cancel, handler: {
            _ in
            guard let field = alert.textFields?.first, let text = field.text, !text.isEmpty else {
                return
            }
            self?.createItem(name: text)
        }))
        present(alert, animated: true)
        
    }

【问题讨论】:

  • 删除“?”来自self?.createItem(name: text)。它看起来像:self.createItem(name: text)
  • 阅读更多关于 swift 中的弱自我

标签: ios swift uikit


【解决方案1】:

问题在于您没有将 self 变量声明为弱变量以使其成为可选变量。如下使用弱 self 使 ViewController 的 self 实例成为可选。然后你就可以使用问号了。

@objc private func didTapAdd() {
        let alert = UIAlertController(title: "New Item", message: "Enter new Item", preferredStyle: .alert)
        alert.addTextField(configurationHandler: nil)
        alert.addAction(UIAlertAction(title: "Submit", style: .cancel, handler: { [weak self] (_) in
            guard let field = alert.textFields?.first, let text = field.text, !text.isEmpty else {
                return
            }
            self?.createItem(name: text)
        }))
        present(alert, animated: true)
        
    }

【讨论】:

  • @sokoine 如果它解决了您的问题,请将答案标记为已接受:)
猜你喜欢
  • 1970-01-01
  • 2020-02-03
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多