[swift-evolution] [pitch] Printing versions of try! and try?

Erica Sadun erica at ericasadun.com
Sat Jan 30 23:41:38 CST 2016


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
    }
}


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160130/5e3c836f/attachment.html>


More information about the swift-evolution mailing list