Last active
December 24, 2016 22:19
-
-
Save andersio/8f0ae67255b959e227aabb4944fa5b6d 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
| let username = MutableProperty("") | |
| let mutableView = username | |
| .validate { $0.characters.count >= 3 ? .success() : .failure(FormError("At least three characters.")) } | |
| .validate { !$0.characters.contains("@") ? .success() : .failure(FormError("Contains invalid characters.")) } | |
| .map(forward: { $0.isEmpty ? "" : "\($0)@reactiveswift" }, | |
| attemptBackward: { Result($0.stripSuffix("@reactiveswift"), failWith: FormError("Missing `@reactiveswift` suffix.")) }) | |
| mutableView.validations.observeValues { print("error: \($0.error?.reason ?? "NoError")") } | |
| mutableView.value = "ya" // At least three characters. | |
| print("value: \(username.value)") // "" | |
| mutableView.value = "anders@reactiveswift" // NoError | |
| print("value: \(username.value)") // "anders" | |
| mutableView.value = "anders@@reactiveswift" // Contains invalid characters. | |
| print("value: \(username.value)") // "anders" | |
| struct FormError: Error { | |
| let reason: String | |
| init(_ reason: String) { | |
| self.reason = reason | |
| } | |
| } | |
| extension String { | |
| func stripSuffix(_ suffix: String) -> String? { | |
| if let range = range(of: suffix) { | |
| return substring(with: startIndex ..< range.lowerBound) | |
| } | |
| return nil | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment