Skip to content

Instantly share code, notes, and snippets.

@werediver
Last active July 3, 2017 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save werediver/f3a8181f22c6c3b8fb27f3ebe09a06c9 to your computer and use it in GitHub Desktop.
Save werediver/f3a8181f22c6c3b8fb27f3ebe09a06c9 to your computer and use it in GitHub Desktop.
Better `fatalError()`.
import Foundation
func fatalError<T>(@autoclosure message: () -> String = "", file: StaticString = #file, line: UInt = #line) -> T {
fatalError(message(), file: file, line: line)
}
// Demo
protocol ResultType {
associatedtype V
var value: V? { get }
var error: ErrorType? { get }
}
enum Result<V>: ResultType {
case Value(V)
case Error(ErrorType)
var value: V? {
switch self {
case let .Value(value):
return value
default:
return nil
}
}
var error: ErrorType? {
switch self {
case let .Error(error):
return error
default:
return nil
}
}
init(value: V) {
self = .Value(value)
}
init<R: ResultType where R.V == V>(sourceResult r: R) {
self = r.value.map { .Value($0) } ?? r.error.map { .Error($0) } ?? fatalError() // LOOK HERE
}
}
struct InvalidResult<V>: ResultType {
var value: V? { return nil }
var error: ErrorType? { return nil }
}
print(Result(Result.Value("OK")))
print(Result(InvalidResult<()>()))
/*
Value("OK")
fatal error: : file /var/folders/mz/4rdq8yg95v56bhbndfvnr7z4lwl1px/T/lldb/70553/playground36.swift, line 40
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment