import Foundation
struct Person {
let name: String
var age: Int
}
struct PersonViewModel {
var name: String?
var age: String?
enum InputError: Error {
case InputMissing
case AgeIncorrect
}
func createPerson() throws -> Person {
guard let age = age, let name = name,
name.count > 0 && age.count > 0 else {
throw InputError.InputMissing
}
guard let ageFormatted = Int(age) else {
throw InputError.AgeIncorrect
}
return Person(name: name, age: ageFormatted)
}
}
struct GuardExample {
func example() {
do {
let personVM = PersonViewModel(name: "", age: "2")
let person = try personVM.createPerson()
print("Success! Person created. \(person)")
} catch PersonViewModel.InputError.InputMissing {
print("Input missing!")
} catch PersonViewModel.InputError.AgeIncorrect {
print("Age Incorrect!")
} catch {
print("Something went wrong, please try again!")
}
}
}
网友评论