How to Use NSError in Swift
Step 1: declare the NSError variable. Must be added ?, Do not add or add! None. Optional is used, so var is used instead of let.
var error: NSError?
Step 2: Add & before the variable when using it &.
NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &error)
The previous pitfalls were NSError !, Compiler veteran cocould not find member MutableContainers to lure my errors elsewhere.
In Objective-C, the type of the method that accepts NSError is (NSError **), and the compiler converts it to (NSError * _ autoreleasing *).
In Swift, the type of NSError accepted by the method is (NSErrorPointer), and The NSErrorPointer is AutoreleasingUnsafeMutablePointer. . (Alias)
typealias NSErrorPointer = AutoreleasingUnsafeMutablePointer
AutoreleasingUnsafeMutablePointer It is actually a struct.
The following is a simple example.
let jsonString = [{ame:enson,age:25}]let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)var error: NSError?let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers, error: &error)if let error = error { println(error.localizedDescription)}println(jsonObject)
WWDC2015 introduced Swift2.0 and announced open source at the end of the year. One new feature is the Error Handling Model. We can use do try catch to handle methods that may throw errors. Many methods in OC that contain NSError parameters are no longer converted to Swift2.0. Instead, the method declares an error (throws ).