我有一個擴展,我使用獨立的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