Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created October 22, 2019 15:17
Show Gist options
  • Save digoreis/0abcaa06fa5f932b0071e9a2155b3a68 to your computer and use it in GitHub Desktop.
Save digoreis/0abcaa06fa5f932b0071e9a2155b3a68 to your computer and use it in GitHub Desktop.
import Cocoa
@propertyWrapper
struct Clapping<Value: Comparable> {
var value: Value
let range: ClosedRange<Value>
init(wrappedValue: Value, _ range: ClosedRange<Value>) {
precondition(range.contains(wrappedValue))
self.value = wrappedValue
self.range = range
}
var wrappedValue: Value {
get { value }
set { value = min(max(range.lowerBound, newValue), range.upperBound)}
}
}
@propertyWrapper
struct StringValidator<Value: StringProtocol> {
var value: Value
let regex: String
init(wrappedValue: Value, _ regex: String) {
let emailPred = NSPredicate(format:"SELF MATCHES %@", regex)
precondition(emailPred.evaluate(with: wrappedValue) || wrappedValue == "")
self.value = wrappedValue
self.regex = regex
}
var wrappedValue: Value {
get { value }
set {
let emailPred = NSPredicate(format:"SELF MATCHES %@", regex)
if emailPred.evaluate(with: newValue) {
value = newValue
} else {
value = ""
}
}
}
}
struct Solution {
@Clapping(0...14) var pH: Double = 7.0
@StringValidator("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}") var email: String = ""
}
var solution = Solution(pH: 7.0, email: "")
solution.pH = 20
solution.email = "digo.reis@gmail.com"
print(solution.email)
solution.email = "digo.reis.com"
print(solution.email)
solution.email = "digo.reis@gmail.com"
print(solution.email)
solution.email = "rr@test.com"
print(solution.email)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment