Skip to content

Instantly share code, notes, and snippets.

@Nirma
Last active April 27, 2019 08:58
Show Gist options
  • Save Nirma/6c59cbc6a7c8f6bcf39fc19fe8e1eae2 to your computer and use it in GitHub Desktop.
Save Nirma/6c59cbc6a7c8f6bcf39fc19fe8e1eae2 to your computer and use it in GitHub Desktop.
Supporting code examples for blog post "Learning to love Result"
enum CactusError: Error {
case cactusNotFound
}
var nearestCactusDistanceKm: Result<Int, CactusError> = .success(33)
let distance = nearestCactusDistanceKm.map { "The nearest Cactus is within \($0) km " }
struct CardboardBox: Codable {
let brand: String
let width: Double
let height: Double
let depth: Double
let flavor: String?
}
let validBoxJSON = """
{
"flavor": "Musty with undertones of cherry and an aftertaste of wet river rock, NOT dry river rock.",
"brand": "Nick's Fancy Boxes",
"width": 5,
"height": 5,
"depth": 5
}
"""
do {
let box = try JSONDecoder().decode(CardboardBox.self, from: validBoxJSON.data(using: .utf8)!)
print(box.brand)
} catch {
print("There was an error parsing the JSON")
}
let inValidBoxJSON = """
{
"flavor": 42,
"brand": "The Best Brand",
"width": 5,
"height": 5,
"depth": 5
}
"""
if let data = inValidBoxJSON.data(using: .utf8) {
let myBoxResult = Result {
try JSONDecoder().decode(CardboardBox.self, from: data)
}
switch myBoxResult {
case .success(let box):
print(" -- My box --\n\n \(box)")
case .failure(let failure):
print(failure.localizedDescription)
}
}
enum Result<T, E: Error> {
case success(T)
case error(E)
}
// Numeric Password
register(password: "8675309999999") // nil
// No numbers
register(password: "superduperpassword") // nil
// Too Short
register(password: "Swiftdud3") // niil
enum PasswordError: Error {
case tooShort
case strictlyNumeric
case noUppercaseLetters
case noLowerCaseLetters
var failureMessage: String {
switch self {
case .lessThanTenCharacters:
return "Password must contain ten characters or more."
case .noNumericCharacters:
return "Password must contain numeric characters."
case .strictlyNumeric:
return "Password must contain both upper and lowercase characters."
case .noUppercaseLetters:
return "Password must contain upper case characters."
case .noLowerCaseLetters:
return "Password must contain lower case characters."
}
}
}
// Numeric Password
register(password: "8675309999999") // .failure(.strictlyNumeric)
// No numbers
register(password: "superduperpassword") // .noNumericCharacters
// Too Short
register(password: "Swiftdud3") // .lessThanTenCharacters
func register(password: String) -> Result<String, PasswordError> {
if password.count < 10 {
return .failure(.lessThanTenCharacters)
}
if !password.contains(where: { ("0"..."9").contains($0)}) {
return .failure(.noNumericCharacters)
}
let noLowerCaseCharacters = !password.contains(where: { ("a"..."z").contains($0) })
let noUpperCaseCharacters = !password.contains(where: { ("A"..."Z").contains($0) })
if noLowerCaseCharacters && noUpperCaseCharacters {
return .failure(.strictlyNumeric)
}
if noLowerCaseCharacters {
return .failure(.noLowerCaseLetters)
}
if noUpperCaseCharacters {
return .failure(.noUppercaseLetters)
}
return .success("Password Registered!")
}
func register(password: String) -> (success: String?, error: String?) {
...
}
func register(password: String) -> String? {
if password.count < 10 {
return nil
}
if !password.contains(where: { ("0"..."9").contains($0)}) {
return nil
}
if !password.contains(where: { ("a"..."z").contains($0) }) {
return nil
}
if !password.contains(where: { ("A"..."Z").contains($0) }) {
return nil
}
return "Password registered!"
}
switch result {
case .success(let message):
handleSuccess(with: message)
case .failure(let failure):
retry(with: failure.message)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment