Skip to content

Instantly share code, notes, and snippets.

@zwaldowski
Created February 5, 2018 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zwaldowski/eb69d5374cbf934dc22585e790f8b90e to your computer and use it in GitHub Desktop.
Save zwaldowski/eb69d5374cbf934dc22585e790f8b90e to your computer and use it in GitHub Desktop.
Non-nil validation using KeyPath
import Foundation
struct Test {
var a: String?
var b: Int?
var c: NSObject?
var x = 42
enum Error: Swift.Error {
case missingProperty(PartialKeyPath<Test>)
}
func validate(_ requiredProperties: Set<PartialKeyPath<Test>>) throws {
for property in requiredProperties {
let mirror = Mirror(reflecting: self[keyPath: property])
guard mirror.displayStyle == .optional, mirror.children.isEmpty else { continue }
throw Error.missingProperty(property)
}
}
}
var x = Test()
x.a = "foo"
//x.b = 42
x.c = NSObject()
do {
try x.validate([ \Test.a, \Test.b, \Test.c, \Test.x ])
} catch Test.Error.missingProperty(let property) {
print("\(property) not set") // Swift.WritableKeyPath<Test, Swift.Optional<Swift.Int>> not set
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment