Learn Swift from scratch (Day 52)-Cocoa error handling mode
The Swift error handling mode is different in Swift1.x and Swift 2.0.
The error handling mode of Swift 1.x Code adopts the Cocoa framework error handling mode. Currently, Objective-C still adopts this mode, while the do-try-catch error processing mode is adopted after Swift2.0.
The following sample code reads a string from the file to the memory. If you use the Swift 1.x error handling mode, the Code is as follows:
Import Foundation var err: NSError? // Define the optional NSError? Variable let contents = NSString (contentsOfFile: filePath, incluencoding: NSUTF8StringEncoding, error: & err) if err! = Nil {// determine whether the err variable is still nil // handle the error}
NSError? It must be an optional variable because it must be initialized as nil.
Determine whether the err variable is still nil. If it is still nil in the code
let contents = NSString(contentsOfFile: filePath, ê encoding: NSUTF8StringEncoding, error: &err)
No error occurs during method calling. Otherwise, an error occurs.
The constructor of the above Code. Its Swift syntax is defined as follows:
init?(contentsOfURL url: NSURL, encoding enc: UInt, error error: NSErrorPointer)
The last parameter of the constructor is NSErrorPointer (NSError pointer). In actual calls, we need to pass the err variable address (that is, & err), and The & is the get address character. If an error occurs after the method is called, The err variable is assigned a value.