Skip to content

Instantly share code, notes, and snippets.

@dennislysenko
Created December 13, 2015 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dennislysenko/8bd2919b329514369b94 to your computer and use it in GitHub Desktop.
Save dennislysenko/8bd2919b329514369b94 to your computer and use it in GitHub Desktop.
// Setup: We want to arm a NuclearWarhead and get a LaunchCode from it but there's a 1/10 chance of a PrematureDetonationError
// (nb: if Swift had any kind of useful random generator that I could pick up in 5 seconds I would use that instead of this pseudorandom-at-best algorithm)
struct NuclearWarhead {}
struct LaunchCode {}
struct PrematureDetonationError: ErrorType {}
func armNuclearWarhead(warhead: NuclearWarhead) throws -> LaunchCode {
let currentTimestamp = NSDate().timeIntervalSince1970
let lastDigit = currentTimestamp % 10
if lastDigit == 8 {
// looks like someones about to get hurt
throw PrematureDetonationError()
} else {
return LaunchCode()
}
}
let warhead = NuclearWarhead()
// traditional
do {
let launchCode = try armNuclearWarhead(warhead)
print(launchCode)
} catch let error {
print(String(reflecting: error))
}
// Notice that armNuclearWarhead is a synchronous function
// Synchronous flow is arguably much more readable, and isn't a straight shot to callback hell (or indentation purgatory)
// So if we accept that it's generally better to write synchronous code, that's great and all, but what if arming it takes a few seconds? We'd want to call it async
// But it's a throwing function and dealing with do/try/catch + asynchronous dispatch takes us straight back to the callback-hell-dilemma...
// So let's use promises
let launchCode = =>{
try armNuclearWarhead(warhead)
}
launchCode.await { result in
switch result {
case .Success(let launchCode):
print(launchCode)
case .Failure(let error):
print(String(reflecting: error))
}
}
// Oh and if we don't want to deal with do/try/catch but still want to call it synchronously...
switch <=launchCode {
case .Success(let launchCode):
print(launchCode)
case .Failure(let error):
print(String(reflecting: error))
}
@dennislysenko
Copy link
Author

Did I actually just forget to include the code that I'm showing an example usage of

@dennislysenko
Copy link
Author

no words

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