OptionalConstraint
public struct OptionalConstraint<T, E> : Constraint where E : Error
A Constraint
that accepts an optional input and passes the unwrapped value to an underlying Constraint
.
enum Failure: Error {
case required
case invalidEmail
}
let email: String? = "hello@nsagora.com"
let constraint = OptionalConstraint<String, Failure>(required: .required) {
PredicateConstraint(EmailPredicate(), error: .invalidEmail)
}
let result = constraint.evaluate(with: email)
-
Declaration
Swift
public typealias InputType = T?
-
Declaration
Swift
public typealias ErrorType = E
-
Returns a new
OptionalConstraint
instance.enum Failure: Error { case required case invalidEmail }
let email: String? = "hello@nsagora.com" let emailConstraint = PredicateConstraint(EmailPredicate(), error: .invalidEmail) let constraint = OptionalConstraint<String, Failure>(required: .required, constraint: emailConstraint) 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 init<C>(required requiredError: E? = nil, constraint: C) where T == C.InputType, E == C.ErrorType, C : Constraint
-
Returns a new
OptionalConstraint
instance.enum Failure: Error { case required case invalidEmail }
let email: String? = "hello@nsagora.com" let constraint = OptionalConstraint<String, Failure>(required: .required) { PredicateConstraint(EmailPredicate(), error: .invalidEmail) } let result = constraint.evaluate(with: email) - parameter required: An optional `Error` that marks the optional as mandatory. - parameter constraint: A closure that dynamically builds a `Constraint` to describes the evaluation rule for the unwrapped value of the input.
Declaration
Swift
public init<C>(required requiredError: E? = nil, constraintBuilder: () -> C) where T == C.InputType, E == C.ErrorType, C : Constraint
-
Evaluates the unwrapped input on the underlying constraint.
Declaration
Swift
public func evaluate(with input: T?) -> Result<Void, Summary<E>>
Parameters
input
The optional input to be validated.
Return Value
.failure
with aSummary
containing the required error when the optional is marked as required and the input isnil
,success
when the optional is not marked as required and the input isnil
, the evaluation result from the underlying constraint otherwise.