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

问题描述:

let alertController = UIAlertController(title: "Email?", message: "Please input your email:", preferredStyle: .alert) 



     let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (_) in 
      if let field = alertController.textFields?[0] { 
       // store your data 
       UserDefaults.standard.set(try.text, forKey: "userEmail") 
       UserDefaults.standard.synchronize() 
      } else { 
       // user did not fill field 
      } 
     } 

     let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } 
     alertController.addTextField { (textField) in 
      textField.placeholder = "Email" 
     } 


     alertController.addAction(confirmAction) 
     alertController.addAction(cancelAction) 

     self.present(alertController, animated: true, completion: nil) 
+0

在此添加一些文本。问题的标题并不意味着除代码之外的唯一文本。 – Aziuth

+0

问题是什么? – JeremyP

错字:

UserDefaults.standard.set(field.text, forKey: "userEmail") 

而不是

UserDefaults.standard.set(try.text, forKey: "userEmail") 

错误消息指出它:

... value of type '(_) throws ->()'

+0

这是我认为的正确答案。 'try'使它看起来像编译器正在抛出一样。 – JeremyP

使用这个....

let confirmAction = UIAlertAction(title: "Confirm", style: .default) { (action) -> Void in 
     if let field = alertController.textFields?[0] { 
      // store your data 
      UserDefaults.standard.set(try.text, forKey: "userEmail") 
      UserDefaults.standard.synchronize() 
     } else { 
      // user did not fill field 
     } 
    } 

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in 
    alertController.addTextField { (textField) in 
     textField.placeholder = "Email" 
    })