Constraint

public protocol Constraint : AsyncConstraint

The Constraint protocol is used to define the structure that must be implemented by concrete constraints.

  • A type that provides information about what kind of values the constraint can be evaluated with.

    Declaration

    Swift

    associatedtype InputType
  • An error type that provides information about why the evaluation failed.

    Declaration

    Swift

    associatedtype ErrorType
  • Evaluates the input against the receiver.

    Declaration

    Swift

    func evaluate(with input: InputType) -> Result<Void, Summary<ErrorType>>

    Parameters

    input

    The input to be validated.

    Return Value

    .success if the input is valid,.failure containing the Summary of the failing Constraints otherwise.

  • erase() Extension method

    Wraps this constraint with a type eraser.

    enum Failure: Error {
        case notEven
    }
    
    let constraint = BlockConstraint<Int, Failure> {
        $0 % 2 == 0
    } errorBuilder: {
        .notEven
    }
    
    var erasedConstraint = constraint.erase()
    erasedConstraint.evaluate(with: 5)
    

    Declaration

    Swift

    public func erase() -> AnyConstraint<InputType, ErrorType>

    Return Value

    An AnyConstraint wrapping this constraint.

  • Asynchronous evaluates the input against the receiver.

    Declaration

    Swift

    func evaluate(with input: InputType, queue: DispatchQueue, completionHandler: @escaping (_ result: Result<Void, Summary<ErrorType>>) -> Void)

    Parameters

    input

    The input to be validated.

    queue

    The queue on which the completion handler is executed.

    completionHandler

    The completion handler to call when the evaluation is complete. It takes a Bool parameter:

    result

    .success if the input is valid, .failure containing the Summary of the failing Constraints otherwise.

Constraint modifiers

  • optional(required:) Extension method

    Returns a new OptionalConstraint instance.

    enum Failure: Error {
        case required
        case invalidEmail
    }
    
    let email: String? = "hello@nsagora.com"
    let emailConstraint = PredicateConstraint(.email, error: .invalidEmail)
    let constraint = emailConstraint.optional(required: .required)
    
    let result = constraint.evaluate(with: email)
    
    - parameter required: An optional `Error` that marks the optional as mandatory.
    - parameter constraint: A `Constraint` to describes the evaluation rule for the unwrapped value of the input.
    

    Declaration

    Swift

    public func optional<T, E>(required requiredError: E? = nil) -> OptionalConstraint<T, E> where T == Self.InputType, E == Self.ErrorType