Skip to content

Instantly share code, notes, and snippets.

@parthjdabhi
Forked from werediver/FatalError+Ext.swift
Created July 3, 2017 09:05
Show Gist options
  • Save parthjdabhi/46ee76f4fe3bfb75e8009938e5fc56c1 to your computer and use it in GitHub Desktop.
Save parthjdabhi/46ee76f4fe3bfb75e8009938e5fc56c1 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