Swift 惯用的错误检查 [英] Swift idiomatic error checking

查看:19
本文介绍了Swift 惯用的错误检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设你有一个这样的函数:

Let's say that you have a function like this:

func getSomething(error: NSErrorPointer) -> Something

并且您通常以这种方式使用它:

and you typically use it this way:

var error : NSError? = nil
let a = getSomething(&error)

这里检查错误的惯用方法是什么?更具体的问题:

What is an idiomatic way to check for error here? More specific questions:

  1. 如果 error == nil 我们可以假设 a 永远不会为零,反之亦然反之?
  2. 我们应该首先检查什么:error(为了它的零)或 a(为了确认它不是零)?
  3. 可以 a != nil &&error != nil 在某些情况下是真的吗?
  1. If error == nil can we assume that a will never be nil and vice versa?
  2. What should we check first: error (for its nilness) or a (to confirm that it's not a nil)?
  3. Can a != nil && error != nil be true in some cases?

谢谢!

推荐答案

比较 处理方法返回的错误对象在错误处理编程指南"中:

Compare Handling Error Objects Returned From Methods in the "Error Handling Programming Guide":

重要提示:成功或失败由返回值指示方法.虽然 Cocoa 方法在Cocoa 错误域保证返回这样的对象,如果方法通过直接返回 nil 或 NO 来指示失败,你应该在尝试之前,请始终检查返回值是否为 nil 或 NO对 NSError 对象做任何事情.

Important: Success or failure is indicated by the return value of the method. Although Cocoa methods that indirectly return error objects in the Cocoa error domain are guaranteed to return such objects if the method indicates failure by directly returning nil or NO, you should always check that the return value is nil or NO before attempting to do anything with the NSError object.

因此对于 Cocoa/Cocoa Touch 方法,您应该始终检查返回价值第一.如果方法失败,保证 error != nil,但如果方法成功,则不明确保证 error == nil.

So for Cocoa/Cocoa Touch methods you should always check the return value first. It is guaranteed that error != nil if the method fails, but it is not explicitly guaranteed that error == nil if the method succeeds.

示例:

JSON 序列化

var error : NSError?
if let jsonObj = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) {
    // success
} else {
    // failure
    println("Invalid JSON data: (error!.localizedDescription)")
}

核心数据获取请求

var error : NSError?
if let result = context.executeFetchRequest(request, error: &error) {
    // success, result has zero or more elements
} else {
    // failure
    println("Fetch failed: (error!.localizedDescription)")
}

复制文件

var error : NSError?
if !NSFileManager.defaultManager().copyItemAtPath(srcPath, toPath: dstPath, error: &error) {
    println("Cannot copy file: (error!.localizedDescription)")
}

当然你可以为自己的函数定义自己的规则,但我会遵循相同的 Apple 指南.

Of course you can define your own rules for your own functions, but I would follow the same Apple guidelines.

更新:从 Swift 2 开始, 产生错误的 Cocoa 方法是转换为抛出错误的 Swift 函数,并且此错误必须使用 try-catch 处理.这是 Swift 2 版本以上示例:

Update: As of Swift 2, Cocoa methods that produce errors are translated to Swift functions that throw an error, and this error must be handled with try-catch. Here is the Swift 2 version of above examples:

JSON 序列化

do {
    let jsonObj = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
    // success
} catch let error as NSError {
    // failure
    print("Invalid JSON data: (error.localizedDescription)")
}

核心数据获取请求

do {
    let result = try context.executeFetchRequest(request)
    // success, result has zero or more elements
} catch let error as NSError {
    // failure
    print("Fetch failed: (error.localizedDescription)")
}

复制文件

do {
    try NSFileManager.defaultManager().copyItemAtPath(srcPath, toPath: dstPath)
} catch let error as NSError {
    print("Cannot copy file: (error.localizedDescription)")
} 

这篇关于Swift 惯用的错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆