swift guard.swift
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift guard.swift相关的知识,希望对你有一定的参考价值。
struct Person {
let name: String
var age: Int
}
struct PersonViewModel {
var name: String?
var age: String?
enum InputError: ErrorType {
case InputMissing
case AgeIncorrect
}
func createPerson() throws -> Person {
guard let age = age, let name = name
where name.characters.count > 0 && age.characters.count > 0 else {
throw InputError.InputMissing
}
guard let ageFormatted = Int(age) else {
throw InputError.AgeIncorrect
}
return Person(name: name, age: ageFormatted)
}
}
// usage
do {
let person = try personViewModel.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 guard.swift的主要内容,如果未能解决你的问题,请参考以下文章
Swift 反射
Swift入门系列--Swift官方文档(2.2)--中文翻译--About Swift 关于Swift
swift 示例BS swift.swift
swift swift_bug.swift
ios 整理(一)swift和oc的区别
swift swift_extension5.swift