Created
August 7, 2021 05:41
-
-
Save JarvisTheAvenger/f4ceb135026007dfb95309087784a6cc 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
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