Skip to content

Instantly share code, notes, and snippets.

@Terriermon
Created June 17, 2020 08:48
Show Gist options
  • Select an option

  • Save Terriermon/0fa20dae02fed0c39b4bfe54e7db50b8 to your computer and use it in GitHub Desktop.

Select an option

Save Terriermon/0fa20dae02fed0c39b4bfe54e7db50b8 to your computer and use it in GitHub Desktop.
protocol Validatable { }
extension Int: Validatable { }
extension String: Validatable { }
protocol ValidatorConvertible {
associatedtype ValidationType
func validated(_ value: ValidationType) -> Promise<ValidationType>
}
protocol ValidationError: Error {
var message: String { get}
}
struct AnyValidatorConvertible<ValidationType> where ValidationType: Validationable {
private let validated: (ValidationType) -> Promise<ValidationType>
init<Validator: ValidatorConvertible>(_ validator: Validator) where Validator.ValidationType == ValidationType {
self.validated = validator.validated
}
}
extension AnyValidatorConvertible: ValidatorConvertible {
func validated(_ value: ValidationType) -> Promise<ValidationType> {
self.validated(value)
}
}
struct PhoneValidator: ValidatorConvertible {
func validated(_ value: String) -> Promise<String> {
return .value(value)
}
}
struct LoginValidatorFactory {
enum LoginValidatorType {
case age
case phone
case password
}
static func validatorFor<T: Validationable>(type: LoginValidatorType) -> AnyValidatorConvertible<T>? {
switch type {
case .phone:
let anyPhone = AnyValidatorConvertible(PhoneValidator())
return anyPhone
default:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment