The swift error handling mode in swift1.x and Swift 2.0 is different in both modes.
The Swift 1.x code error handling mode uses the Cocoa Framework error-handling mode, which is now used by Objective-c, and the do-try-catch error-handling mode is adopted after Swift2.0 .
The following example code reads a string from a file into memory if you use the Swift 1.x error-handling mode code as follows:
- Import Foundation
- var err:nserror? Define optional Nserror? variables
- Let contents = nsstring (contentsoffile:filepath,
- êencoding:nsutf8stringencoding, Error: &err)
- If err! = Nil {//determine if the ERR variable is still nil
- Error handling
- }
Nserror? must be an optional variable, because you want to initialize it to nil.
Determine If the ERR variable is still nil, if it is nil in the code
- Let contents = nsstring (contentsoffile:filepath,
- êencoding:nsutf8stringencoding, Error: &err)
No error occurred during method call, otherwise an error occurred.
The constructor for 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 (that is , the nserror pointer), then we need to pass the Err variable address (that is, &err) in the actual call ,& is the address character. The ERR variable is assigned a value if there is an error after the method call is complete .
Swift-cocoa error Handling Mode-standby