Validating

@dynamicMemberLookup
@propertyWrapper
public struct Validating<Value>

A type that wraps a value of type Value and an associated validator and re-validates every time value is updated.

This type can be used to associate a value and its validation rules and have that value be re-validated every time it changes, check if it is valid and if not, what the validation errors are. It has dynamic member lookup support to provide direct access to the validated value.

Its primary use is as a property wrapper that lets you declaratively validate properties on your types. When used this way, you can access the validated version of your property using the $property syntax.

struct MyViewModel {
    @Validating(.hasLengthOf(.atLeast(6))
    var password: String = ""
}

var viewModel = MyViewModel()
viewModel.$password.isValid // returns false
viewModel.password = "mypassword"
viewModel.$password.isValid // returns true
  • The wrapped value - changing the value will trigger validation.

    Declaration

    Swift

    public var wrappedValue: Value { get set }
  • Returns the validatedValue when using $value syntax.

    Declaration

    Swift

    public var projectedValue: Validated<Value, String> { get }
  • Initialises a new instance.

    This method will automatically validate the initial wrappedValue, meaning a validatedValue will be available immediately after initialisation.

    Declaration

    Swift

    public init(wrappedValue: Value, _ validator: ValidatorOf<Value, String>)

    Parameters

    wrappedValue

    The value being wrapped

    validator

    The validator to use every time wrappedValue is changed.

  • A convenience initialiser that takes a variadic list of validators and automatically combines them into a single validator.

    Declaration

    Swift

    public init(wrappedValue: Value, _ validators: ValidatorOf<Value, String>...)
  • Provides dynamic access to the underlying validated value’s properties.

    Declaration

    Swift

    public subscript<T>(dynamicMember keyPath: KeyPath<Validated<Value, String>, T>) -> T { get }