Swift 2 - guard 使用举例

2019-12-31  本文已影响0人  暗物质
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!")
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读