Skip to content

Instantly share code, notes, and snippets.

@JarvisTheAvenger
Created August 7, 2021 05:41
Show Gist options
  • Save JarvisTheAvenger/f4ceb135026007dfb95309087784a6cc to your computer and use it in GitHub Desktop.
Save JarvisTheAvenger/f4ceb135026007dfb95309087784a6cc to your computer and use it in GitHub Desktop.
import Foundation
// Result type is enum with two cases, success and error.
// Introduced in swift 5
enum ScoreboardError: Error {
case serverDown
case badURL
case unknown
}
struct Scoreboard {
let score: Int
}
func fetchScoreBoard(gameID: Int,
completion: @escaping ((Result<Scoreboard, ScoreboardError>) -> Void)) {
// faking network request...
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
let score = Int.random(in: 1...100)
if score >= 35 {
completion(.success(Scoreboard(score: score)))
} else {
completion(.failure(.unknown))
}
}
}
fetchScoreBoard(gameID: 1) { result in
switch result {
case .success(_):
print("congratulations you won!!!")
default:
print("Better luck next time :(")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment