我有一个扩展,我使用独立的swift文件声明了用户在填写注册信息时处理错误。但是,而不是在我的调试返回字符串是我想使用一些警报或imageViews显示取决于错误。问题是我不确定如何通过IBOutlet或在此扩展的返回部分创建警报。例如,如果firstName为空,则会在firstName文本字段附近显示红圈警报(imageView)。也许我的处理错误的架构是错误的,或者有什么办法可以做到这一点?扩展错误处理程序
如果您给我一个正确的方向,找到解决办法,我将不胜感激。
这里是扩展
import UIKit
enum RegistrationErrors: Error {
case invalidFirstName
case invalidLastName
case invalidCountry
}
extension RegistrationErrors: CustomStringConvertible {
var description: String {
switch self {
case .invalidFirstName:
return "FirstName cannot be empty"
case .invalidLastName:
return "LastName cannot be empty"
case .invalidCountry:
return "Country cannot be empty"
}
}
}
这里是我的代码,我使用这个扩展
func registrationUser(firstName: String, lastName: String, country: String) throws -> (String, String, String) {
guard let firstName = firstNameTextField.text , firstName.characters.count != 0 else {
throw RegistrationErrors.invalidFirstName
}
guard let lastName = lastNameTextField.text , lastName.characters.count != 0 else {
throw RegistrationErrors.invalidLastName
}
guard let country = countryTextField.text , country.characters.count != 0 else {
throw RegistrationErrors.invalidCountry
}
return (firstName, lastName, country)
}
// MARK: Actions
@IBAction func continueBtnTapped(_ sender: Any) {
do {
let (firstName, lastName, country) = try registrationUser(firstName: firstNameTextField.text!, lastName: lastNameTextField.text!, country: countryTextField.text!)
if let currentUser = FIRAuth.auth()?.currentUser?.uid {
DataService.instance.REF_BASE.child("users").child("profile").setValue(["firstName": firstName, "lastName": lastName, "country": country, "userId": currentUser])
performSegue(withIdentifier: "toUsersList", sender: self)
}
} catch let error as RegistrationErrors {
print(error.description)
} catch {
print(error)
}
}
相关:http://stackoverflow.com/questions/39176196/how-to-provide-a-localized-description-with-an-error-type-in-swift。 –
@MartinR事实上,我正在考虑把它作为一个副本。我没有的唯一原因是我不完全确定这是否是OP所要求的。 – matt