[pitch] Printing versions of try! and try?


(Erica Sadun) #1

Not sure where to post this, so starting here. It's a behavior change more than an API change. I'd like to request that try! and try? print errors in debug builds and in the playground. Right now, I use the following work-around.

/// Replacement for `try?` that introduces printing for
/// error conditions instead of discarding those errors
///
/// - Parameter shouldCrash: defaults to false. When set to true
/// will raise a fatal error, emulating try! instead of try?
///
/// ```swift
/// attempt {
/// let mgr = NSFileManager.defaultManager()
/// try mgr.createDirectoryAtPath(
/// "/Users/notarealuser",
/// withIntermediateDirectories: true,
/// attributes: nil)
/// }
/// ```
///
public func attempt<T>(
    line line: Int = __LINE__,
    shouldCrash: Bool = false,
    closure: () throws -> T
    ) -> T?
{
    do {
        
        /// Return executes only if closure succeeds
        return try closure()
        
    } catch {
        
        /// Emulate try! by crashing
        if shouldCrash {
            print("Fatal error on line \(line): \(error)")
            fatalError()
        }
        
        /// Force print and return nil like try?
        print("Error \(line): \(error)")
        return nil
    }
}