Error-Handling in Swift-Language

2019-01-01 12:01发布

I haven't read too much into Swift but one thing I noticed is that there are no exceptions. So how do they do error handling in Swift? Has anyone found anything related to error-handling?

12条回答
余生请多指教
2楼-- · 2019-01-01 12:47

Edit: Although this answer works, it is little more than Objective-C transliterated into Swift. It has been made obsolete by changes in Swift 2.0. Guilherme Torres Castro's answer above is a very good introduction to the preferred way of handling errors in Swift. VOS

It took a bit of figuring it out but I think I've sussed it. It seems ugly though. Nothing more than a thin skin over the Objective-C version.

Calling a function with an NSError parameter...

var fooError : NSError ? = nil

let someObject = foo(aParam, error:&fooError)

// Check something was returned and look for an error if it wasn't.
if !someObject {
   if let error = fooError {
      // Handle error
      NSLog("This happened: \(error.localizedDescription)")
   }
} else {
   // Handle success
}`

Writing the function that takes an error parameter...

func foo(param:ParamObject, error: NSErrorPointer) -> SomeObject {

   // Do stuff...

   if somethingBadHasHappened {
      if error {
         error.memory = NSError(domain: domain, code: code, userInfo: [:])
      }
      return nil
   }

   // Do more stuff...
}
查看更多
看风景的人
3楼-- · 2019-01-01 12:55

What I have seen is that because of the nature of the device you don't want to be throwing a bunch of cryptic error handling messages at the user. That is why most functions return optional values then you just code to ignore the optional. If a function comes back nil meaning it failed you can pop a message or whatever.

查看更多
泪湿衣
4楼-- · 2019-01-01 12:56

Starting with Swift 2, as others have already mentioned, error handling is best accomplished through the use of do/try/catch and ErrorType enums. This works quite well for synchronous methods, but a little cleverness is required for asynchronous error handling.

This article has a great approach to this problem:

https://jeremywsherman.com/blog/2015/06/17/using-swift-throws-with-completion-callbacks/

To summarize:

// create a typealias used in completion blocks, for cleaner code
typealias LoadDataResult = () throws -> NSData

// notice the reference to the typealias in the completionHandler
func loadData(someID: String, completionHandler: LoadDataResult -> Void)
    {
    completionHandler()
    }

then, the call to the above method would be as follows:

self.loadData("someString",
    completionHandler:     
        { result: LoadDataResult in
        do
            {
            let data = try result()
            // success - go ahead and work with the data
            }
        catch
            {
            // failure - look at the error code and handle accordingly
            }
        })

This seems a bit cleaner than having a separate errorHandler callback passed to the asynchronous function, which was how this would be handled prior to Swift 2.

查看更多
不再属于我。
5楼-- · 2019-01-01 12:59

Nice and simple lib to handle exception: TryCatchFinally-Swift

Like a few others it wraps around the objective C exception features.

Use it like this:

try {
    println("  try")
}.catch { e in
    println("  catch")
}.finally {
    println("  finally")
}
查看更多
若你有天会懂
6楼-- · 2019-01-01 13:00

As Guilherme Torres Castro said, in Swift 2.0, try, catch, do can be used in the programming.

For example, In CoreData fetch data method, instead of put &error as a parameter into the managedContext.executeFetchRequest(fetchRequest, error: &error), now we only need to use use managedContext.executeFetchRequest(fetchRequest) and then handle the error with try, catch (Apple Document Link)

do {
   let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as? [NSManagedObject]
   if let results = fetchedResults{
      people = results
   }
} catch {
   print("Could not fetch")
}

If you have already download the xcode7 Beta. Try to search throwing errors in Documentations and API Reference and choose the first showing result, it gives a basic idea what can be done for this new syntax. However, fully documentation is not post for many APIs yet.

More fancy Error Handling techniques can be found in

What's New in Swift (2015 Session 106 28m30s)

查看更多
骚的不知所云
7楼-- · 2019-01-01 13:02

Basic wrapper around objective C that gives you the try catch feature. https://github.com/williamFalcon/SwiftTryCatch

Use like:

SwiftTryCatch.try({ () -> Void in
        //try something
     }, catch: { (error) -> Void in
        //handle error
     }, finally: { () -> Void in
        //close resources
})
查看更多
登录 后发表回答