【问题标题】:ErrorType protocol in weather app天气应用程序中的 ErrorType 协议
【发布时间】:2016-07-01 11:11:11
【问题描述】:

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

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

}

有什么建议吗?

【问题讨论】:

    标签: error-handling swift2 swift-protocols


    【解决方案1】:

    你可以这样做:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      相关资源
      最近更新 更多