iOS bug修复

将可选类型转换为错误抛出

2016-10-31  本文已影响44人  梁杰_numbbbbb

作者:Erica Sadun,原文链接,原文日期:2016-10-07
译者:wiilen;校对:Cee;定稿:CMB

Soroush Khanlou 曾写道:「很多时候我希望可选类型并不存在,“结果” 就只是 “结果”」。

他给了个例子:

struct NilError: Error { }

func throwable<T>( _ block: @autoclosure() -> T?) throws -> T {
    guard let result: T = block() else {
        throw NilError()
    }
    return result
}

let image = try throwable(UIImage(data: imageData))

我对它进行了一些改进:

// 灵感来自 Soroush Khanlou

public enum Throws {
    public struct NilError: Error, CustomStringConvertible {
        public var description: String { return _description }
        public init(file: String, line: Int) {
            _description = "Nil returned at "
                + (file as NSString).lastPathComponent + ":\(line)"
        }
        private let _description: String
    }
    
    public static func this<T>(
        file: String = #file, line: Int = #line,
        block: () -> T?) throws -> T
    {
        guard let result = block() 
            else { throw NilError(file: file, line: line) }
        return result
    }
}

do {
    let imageData = Data()
    let image = try Throws.this { NSImage(data: imageData) }
} catch { print(error) }

两者之间最明显的差别在于我的错误是「Nil return at playground13.swift:24」这种格式的,不过我也正在测试不同的风格,并以此来添加一些信息:

各位有什么想法吗?

更新:Loic 给出了另一种实现,给了我一些启发:

public struct NilError: Error, CustomStringConvertible {
    public var description: String { return _description }
    public init(file: String, line: Int) {
        _description = "Nil returned at "
            + (file as NSString).lastPathComponent + ":\(line)"
    }
    private let _description: String
}

extension Optional {
    public func unwrap(file: String = #file, line: Int = #line) throws -> Wrapped {
        guard let unwrapped = self else { throw NilError(file: file, line: line) }
        return unwrapped
    }
}

do {
    let imageData = Data()
    let image = try NSImage(data: imageData).unwrap()
} catch { print(error) }

本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权,最新文章请访问 http://swift.gg

上一篇下一篇

猜你喜欢

热点阅读