美文网首页
Swift 2 - guard 使用举例

Swift 2 - guard 使用举例

作者: 暗物质 | 来源:发表于2019-12-31 13:46 被阅读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!")
        }
    }
}

相关文章

网友评论

      本文标题:Swift 2 - guard 使用举例

      本文链接:https://www.haomeiwen.com/subject/njmboctx.html