Created
February 5, 2018 15:02
-
-
Save zwaldowski/eb69d5374cbf934dc22585e790f8b90e to your computer and use it in GitHub Desktop.
Non-nil validation using KeyPath
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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