繁体   English   中英

无法将类型 '(_) throws -> ()' 的值转换为预期的参数类型 '((UIAlertAction) -> Void)?'

[英]Cannot convert value of type '(_) throws -> ()' to expected argument type '((UIAlertAction) -> Void)?'

首先,非常感谢您对我的帮助。 我不明白这个错误,也找不到解决办法。

我看过其他答案,但它们似乎没有帮助。 这是我的代码。 错误显示在 let 操作行上。

  @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

    var textField = UITextField()

    let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert)


    let action = UIAlertAction(title: "Add item", style: .default) { (UIAlertAction) in





        //what will happen once the user clicks the Add Item button on our UIAlert

        let newItem = item()
        newItem.title = textField.text!
        self.itemArray.append(newItem)

   let encoder = PropertyListEncoder()

        do {

        let data = try encoder.encode(self.itemArray)
        }

        catch {

            try Data.write(to: self.dataFilePath!)
            print("Error encoding item array, \(error)")

        }


        //reloads table view data
        self.tableView.reloadData()

      }

alert.addTextField { (alertTextField) in

        alertTextField.placeholder = "What Needs To Be Done?"
      textField = alertTextField
    }

alert.addAction(action)
  present(alert, animated: true, completion: nil)

}

错误:无法将类型“(_) throws -> ()”的值转换为预期的参数类型“((UIAlertAction) -> Void)?”

三个问题:

  1. 动作中的参数必须是实例,而不是类型

    let action = UIAlertAction(title: "Add item", style: .default) { action in

    或者如果操作未使用

    let action = UIAlertAction(title: "Add item", style: .default) { _ in
  2. Data.write(to:..必须是data.write(to:..

  3. 第三个问题导致(有点误导)错误消息: data行必须在do块内。 错误表明try语句周围没有do

    do { let data = try encoder.encode(self.itemArray) try data.write(to: self.dataFilePath!) } catch { print("Error encoding item array, \\(error)") }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM