Swift惯用错误检查 [英] Swift idiomatic error checking
问题描述
func getSomething(error:NSErrorPointer) - >一些东西
,你通常用这种方法:
var error:NSError? = nil
let a = getSomething(& error)
什么是惯用的方式在这里检查错误?更具体的问题:
- 如果
error == nil
我们可以假设a
永远不会是零和副$ b $反之亦然? - 我们应该先检查一下:
code>(为零)或
a
(
确认它不是零)? - 可以
a!= nil&&&错误!= nil
在某些情况下为true?
谢谢!
比较处理从方法返回的错误对象
在错误处理编程指南中:
重要提示:
方法的返回值表示成功或失败。虽然Cocoa方法间接返回
中的错误对象Cocoa错误域保证返回这样的对象,如果
方法通过直接返回nil或NO表示失败,您应该
始终检查返回尝试
之前,值为零或否,对NSError对象执行任何操作。
所以对于Cocoa / Cocoa Touch方法应该首先检查返回
值。确保 error!= nil
如果方法失败,
但是没有明确保证 error == nil
如果方法成功。
示例:
JSON序列化
var error:NSError?
如果让jsonObj = NSJSONSerialization.JSONObjectWithData(jsonData,options:nil,error:& error){
// success
} else {
// failure
println(无效的JSON数据:\(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(Can not copy file:\(error!.localizedDescription))
}
当然,您可以为自己的功能定义自己的规则,
我将遵循相同的苹果指南。
更新:从Swift 2开始, Cocoa方法产生错误的是
转换为Swift函数,这会导致错误,而这个错误
必须使用 try
- catch
。以下是上述示例中的Swift 2版本
:
do {
let jsonObj = try NSJSONSerialization.JSONObjectWithData(jsonData,options:[])
// success
} catch let error as NSError {
// failure
print(无效的JSON数据:\(error.localizedDescription))
}
核心数据提取请求
do {
let result = try context.executeFetchRequest(request)
//成功,结果有零个或多个元素
} catch let error as NSError {
// failure
print (Fetch failed:\(error.localizedDescription))
}
复制文件
do {
try NSFileManager.defaultManager()。copyItemAtPath(srcPath,toPath: dstPath)
}捕获let错误为NSError {
print(无法复制文件:\(error.localizedDescription))
}
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:
- If
error == nil
can we assume thata
will never be nil and vice versa? - What should we check first:
error
(for its nilness) ora
(to confirm that it's not a nil)? - Can
a != nil && error != nil
be true in some cases?
Thank you!
Compare Handling Error Objects Returned From Methods in the "Error Handling Programming Guide":
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.
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.
Examples:
JSON Serialization
var error : NSError?
if let jsonObj = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) {
// success
} else {
// failure
println("Invalid JSON data: \(error!.localizedDescription)")
}
Core Data fetch request
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)")
}
Copying files
var error : NSError?
if !NSFileManager.defaultManager().copyItemAtPath(srcPath, toPath: dstPath, error: &error) {
println("Cannot copy file: \(error!.localizedDescription)")
}
Of course you can define your own rules for your own functions, but I would follow the same Apple guidelines.
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 Serialization
do {
let jsonObj = try NSJSONSerialization.JSONObjectWithData(jsonData, options: [])
// success
} catch let error as NSError {
// failure
print("Invalid JSON data: \(error.localizedDescription)")
}
Core Data fetch request
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)")
}
Copying files
do {
try NSFileManager.defaultManager().copyItemAtPath(srcPath, toPath: dstPath)
} catch let error as NSError {
print("Cannot copy file: \(error.localizedDescription)")
}
这篇关于Swift惯用错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!