I want to create a Validatable
protocol that has two properties: a validator
and an isAbleToProceed
boolean:
protocol Validatable {
var validator: Validator { get set }
var isAbleToProceed: Bool { get set }
}
I want to define different types of Validators
(date of birth validator, email validator, etc.). To do so I created a factory:
protocol Validator {}
struct ValidatorFactory {
internal static let sharedInstance = ValidatorFactory()
func dateOfBirthValidator(minimumAge: Int, maximumAge: Int) -> DateOfBirthValidator {
return DateOfBirthValidator(minimumAge: minimumAge, maximumAge: maximumAge)
}
func driversLicenseValidator(minLicenseDuration: Int) -> DriversLicenseValidator {
return DriversLicenseValidator(minLicenseDuration: minLicenseDuration)
}
}
and this is the implementation of DateOfBirthValidator:
struct DateOfBirthValidator: Validator {
let minimumAge: Int
let maximumAge: Int
func isDateOfBirthValid(date: Date) -> Bool {
if let age = Calendar.current.dateComponents([.year], from: date, to: Date()).year {
return (minimumAge ... maximumAge).contains(age)
} else {
return false
}
}
}
Then I would have a class, ViewController, implementing the Validatable protocol:
class ViewController: Validatable {
// MARK: Internal Properties
internal var validator: DriversLicenseValidator
internal var isAbleToProceed: Bool = false
}
But the compiler would report that ViewController does not conform to
Validatable
(does not have a Validator)
This can be solve if I make Validator
a superclass and all the validators structs turn into classes and inherit from it. But is there a way to make it work with structs and protocols?