Created
October 22, 2019 15:17
-
-
Save digoreis/0abcaa06fa5f932b0071e9a2155b3a68 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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 = "[email protected]" | |
print(solution.email) | |
solution.email = "digo.reis.com" | |
print(solution.email) | |
solution.email = "[email protected]" | |
print(solution.email) | |
solution.email = "[email protected]" | |
print(solution.email) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment