Skip to content

Instantly share code, notes, and snippets.

@olivaresf
Last active November 6, 2019 02:22
Show Gist options
  • Save olivaresf/f6156f4d5ca0f1af161f03246b3e3b8b to your computer and use it in GitHub Desktop.
Save olivaresf/f6156f4d5ca0f1af161f03246b3e3b8b to your computer and use it in GitHub Desktop.
An example on how enums can clean up your code
//
// ViewController.swift
// LambdaEnums
//
// Created by Fernando Olivares on 11/1/19.
// Copyright © 2019 Fernando Olivares. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Registering a User
let api = API()
api.registerUser(username: "fernando", password: "password") { result in
switch result {
case .fail(let error):
print("Error: \(error)")
case .success(let userDictionary):
print("User: \(userDictionary)")
}
}
// Getting all events
// api.getEvents { result in
//
// switch result {
//
// case .fail(let error):
// print("Error: \(error)")
//
// case .success(let events):
// print("Events: \(events)")
// }
// }
}
}
class API {
enum Endpoint {
case registerUser(username: String, password: String)
case getEvents
var url: URL {
let endpoint: String
switch self {
case .getEvents:
endpoint = "events"
case .registerUser:
endpoint = "user"
}
return URL(string: "https://demo0638130.mockable.io/\(endpoint)")!
}
var request: URLRequest {
switch self {
case .getEvents:
return URLRequest(url: url)
case .registerUser(let username, let password):
var request = URLRequest(url: url)
request.httpMethod = "POST"
let requestDataDictionary = [
"username": username,
"password": password,
]
request.httpBody = try! JSONSerialization.data(withJSONObject: requestDataDictionary)
return request
}
}
}
func registerUser(username: String, password: String, completion: @escaping (DuplicateCodeResult) -> () ) {
duplicateCode(endpoint: .registerUser(username: username,
password: password),
completion: completion)
}
enum GetEventsResult {
case fail(Error)
case success([String: Any])
}
func getEvents(completion: @escaping (GetEventsResult) -> () ) {
let url = URL(string: "https://demo0638130.mockable.io/events")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (possibleData, possibleResponse, possibleError) in
// possibleData = nil, possibleResponse = nil, possibleError = nil (doesn't make sense)
// possibleData != nil, possibleResponse = nil, possibleError = nil (successful)
guard possibleError == nil else {
completion(.fail(possibleError!))
return
}
guard let existingData = possibleData else {
// There's no error, but no data either.
completion(.fail(NSError(domain: "Invalid State", code: 1, userInfo: nil)))
return
}
guard let parsedJSON = try! JSONSerialization.jsonObject(with: existingData) as? [String: Any] else {
completion(.fail(NSError(domain: "Invalid Data", code: 2, userInfo: nil)))
return
}
completion(.success(parsedJSON))
}
task.resume()
}
enum DuplicateCodeResult {
case fail(Error)
case success([String: Any])
}
func duplicateCode(endpoint: Endpoint, completion: @escaping (DuplicateCodeResult) -> () ) {
let task = URLSession.shared.dataTask(with: endpoint.request) { (possibleData, possibleResponse, possibleError) in
// possibleData = nil, possibleResponse = nil, possibleError = nil (doesn't make sense)
// possibleData != nil, possibleResponse = nil, possibleError = nil (successful)
guard possibleError == nil else {
completion(.fail(possibleError!))
return
}
guard let existingData = possibleData else {
// There's no error, but no data either.
completion(.fail(NSError(domain: "Invalid State", code: 1, userInfo: nil)))
return
}
guard let parsedJSON = try! JSONSerialization.jsonObject(with: existingData) as? [String: Any] else {
completion(.fail(NSError(domain: "Invalid Data", code: 2, userInfo: nil)))
return
}
completion(.success(parsedJSON))
}
task.resume()
}
}
@mredig
Copy link

mredig commented Nov 5, 2019

Just wanted to suggest naming the gist with .swift on the end and then GitHub should syntax highlight it. :)

@olivaresf
Copy link
Author

Just wanted to suggest naming the gist with .swift on the end and then GitHub should syntax highlight it. :)

Thanks! That's a good idea. I don't have a lot of experience with gists.

@mredig
Copy link

mredig commented Nov 6, 2019

Awesome! Thanks for doing so!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment