Swift惯用错误检查

Swift惯用错误检查

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

问题描述

假设你有这样的功能:

  func getSomething(error:NSErrorPointer) - >一些东西

,你通常用这种方法:

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

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


  1. 如果 error == nil 我们可以假设 a 永远不会是零和副$ b $反之亦然?

  2. 我们应该先检查一下: code>(为零)或 a
    确认它不是零)?

  3. 可以 a!= nil&&&错误!= nil 在某些情况下为true?

谢谢!

解决方案

比较
在错误处理编程指南中:

所以对于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:

  1. If error == nil can we assume that a will never be nil and viceversa?
  2. What should we check first: error (for its nilness) or a (toconfirm that it's not a nil)?
  3. Can a != nil && error != nil be true in some cases?

Thank you!

解决方案

Compare Handling Error Objects Returned From Methodsin the "Error Handling Programming Guide":

So for Cocoa/Cocoa Touch methods you should always check the returnvalue 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 aretranslated to Swift functions that throw an error, and this errormust be handled with try-catch. Here is the Swift 2 versionof 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惯用错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 05:16