error-handling - 天气应用程序中的 ErrorType 协议(protocol)

标签 error-handling swift2 swift-protocols

我对 Swift 很陌生,正在尝试创建天气应用程序。我有协议(protocol) func weatherManagerFailedToLoadCityWithError(error: ErrorType) .在 weatherManager.swift 中有一些委托(delegate)

} else if status == 404 {
                // City not found
                if self.delegate != nil {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.delegate?.weatherManagerFailerToLoadCityWithError(.InvalidResponse)
                    })
                }

            } else {
                // Some other here?
                if self.delegate != nil {
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.delegate?.weatherManagerFailerToLoadCityWithError(.MissingData)
                    })
                }
            }

在这个代码块中我应该怎么做weatherController.swift
func weatherManagerFailedToLoadCityWithError(error: ErrorType) {

}

有什么建议吗?

最佳答案

你可以这样做:

private struct ErrorInformation {
    static let Domain = "us.firmaName"
    static let ServerNotFoundDomain = "\(ErrorInformation.Domain).notFound"
}

private extension NSError {
    static func serverNotFound() -> NSError {
       let userInfo = [
           NSLocalizedDescriptionKey: NSLocalizedString("Server Not Found", comment: ""),
           NSLocalizedFailureReasonErrorKey: NSLocalizedString("The Server you are asking for is not available.", comment: ""),
           NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString("Please proof your URL bla-bla-bla.", comment: "")
       ]

    return NSError(domain: ErrorInformation.ServerNotFoundDomain, code: 404, userInfo: userInfo)
}

然后调用你的函数:
weatherManagerFailedToLoadCityWithError(error: NSError.serverNotFound())

如果你愿意,你可以在你的函数中处理错误:
func weatherManagerFailedToLoadCityWithError(error: ErrorType) {
   print("Error description: \(error.userInfo. NSLocalizedDescriptionKey)")
}

如果您需要更多解释,只需发布​​更多代码。

关于error-handling - 天气应用程序中的 ErrorType 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143936/

相关文章:

swift - 遵守协议(protocol)的误解

ios - 在 iOS Swift 2.1 中适合谷歌地图 View 以包含多边形的最佳方法?

swift - `#selector` 的参数未引用初始化程序或方法

ios - Swift - 调用自定义委托(delegate)方法

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

error-handling - 类型错误 : __init__() got an unexpected keyword argument 'progress_bar_refresh_rate'

stored-procedures - Try/Catch 无法捕获存储过程中的异常

python - “' numpy.ndarray ' object is not callable”

iOS - 表格 View 渲染

协议(protocol) : operator '===' cannot be applied to operands of type '_' and 'Self.T' 中的 Swift 泛型