How to Use NSError in Swift

Source: Internet
Author: User

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 ).

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.