Skip to content

Instantly share code, notes, and snippets.

@andersio
Last active December 24, 2016 22:19
Show Gist options
  • Select an option

  • Save andersio/8f0ae67255b959e227aabb4944fa5b6d to your computer and use it in GitHub Desktop.

Select an option

Save andersio/8f0ae67255b959e227aabb4944fa5b6d to your computer and use it in GitHub Desktop.
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