Created
December 26, 2017 21:12
-
-
Save libdx/adc43586d8de04b3e5d33181fee89643 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
protocol AnyValidator { | |
func validate(any: Any) -> Bool | |
} | |
protocol Validator: AnyValidator { | |
associatedtype Value | |
func validate(value: Value) -> Bool | |
} | |
extension Validator { | |
func validate(any: Any) -> Bool { | |
guard let v = any as? Value else { return false } | |
return validate(value: v) | |
} | |
} | |
final class EmailValidator: Validator { | |
func validate(value: String) -> Bool { | |
return value.contains("@") | |
} | |
} | |
final class MonthValidator: Validator { | |
func validate(value: Int) -> Bool { | |
return 0 < value && value <= 12 | |
} | |
} | |
let emailValidator = EmailValidator() | |
let monthValidator = MonthValidator() | |
let validators: [AnyValidator] = [emailValidator, monthValidator] | |
validators[0].validate(any: "example") | |
validators[0].validate(any: "[email protected]") | |
validators[0].validate(any: 42) | |
validators[1].validate(any: 45) | |
validators[1].validate(any: 6) | |
validators[1].validate(any: "two") | |
let emailValidators: [EmailValidator] = validators.flatMap { guard let v = $0 as? EmailValidator else {return nil}; return v } | |
emailValidators | |
let monthsValidators: [MonthValidator] = validators.flatMap { guard let v = $0 as? MonthValidator else {return nil}; return v } | |
monthsValidators | |
monthsValidators[0].validate(value: 4) | |
//monthsValidators[0].validate(value: "4") // compile error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment