如何使用自定义消息抛出错误消息(即 ErrorType
)?
例如:
catch let error as MyError {
print(error.customMessage)
}
最佳答案
我找到了这个干净的版本。这个想法是同时实现 String 和 ErrorType 协议(protocol)并使用错误的 rawValue。
enum UserValidationError: String, ErrorType {
case NoFirstNameProvided = "Please insert your first name."
case NoLastNameProvided = "Please insert your last name."
case NoAgeProvided = "Please insert your age."
case NoEmailProvided = "Please insert your email."
}
用法:
do {
try User.define(firstName,
lastName: lastName,
age: age,
email: email,
gender: gender,
location: location,
phone: phone)
}
catch let error as User.UserValidationError {
print(error.rawValue)
return
}
关于ios - 使用自定义消息处理错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38835102/