Comparing KeyPaths (generics, protocols with associated type)

Hey! I was experimenting on implementing a simple form validator, that validates a given form and returns invalid fields as KeyPaths and I ran into a confusing situation. My code:

import Foundation

protocol Validatable {
    associatedtype Attachment

    var email: String { get }
    var attachments: [Attachment] { get }
}

struct Validator<Form: Validatable> {
    let form: Form

    func validate() -> [PartialKeyPath<Form>] {
        if form.attachments.isEmpty {
            return [\Form.attachments]
        } else {
            return []
        }
    }
}

struct MyForm: Validatable {
    let email = "valid@gmail.com"
    let attachments: [String] = []
}

let myForm = MyForm()
let validator = Validator(form: myForm)

let invalidFields = validator.validate()
print(invalidFields.first!) // Swift.KeyPath<__lldb_expr_14.MyForm, Swift.Array<Swift.String>>
print(\MyForm.attachments) // Swift.KeyPath<__lldb_expr_14.MyForm, Swift.Array<Swift.String>>
print(invalidFields.first! == \MyForm.attachments) // false

I would expect that last print statement to give me true but that's not the case. Why is that and is there a solution/workaround for this?

Thanks!

Terms of Service

Privacy Policy

Cookie Policy