How to use Nserror in Swift

Source: Internet
Author: User
Tags try catch


Step one: Declare the nserror variable. Be sure to add "?", without adding or adding "!" Not even. Because optional is used, you need to use VAR instead of let.

var error:nserror?

Step Two: Add "&" to the variable before using it.

Nsjsonserialization.jsonobjectwithdata (data!, Options:. Mutablecontainers, Error: &error)

Before the pit was Nserror used is "!", the compiler always said "Could not find member" Mutablecontainers ", the wrong lure me to other places.


In Objective-c, the type of the method that accepts Nserror is (nserror ), and the compiler then converts it to (nserror *__autoreleasing *).

In Swift, the type of method accepts Nserror is (Nserrorpointer), Nserrorpointer is autoreleasingunsafemutablepointer< nserrorThe alias of the?>. (alias)

Typealias Nserrorpointer = autoreleasingunsafemutablepointer<nserror?>

andAutoreleasingunsafemutablepointer<Nserror?> is actually a struct.

Here is a simple example to use.

Let jsonstring = "[{\" name\ ": \" benson\ ", \" age\ ": +]" 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 declared the end of the open source. One of the new features is the error handling Model, where we can use the do try catch to handle methods that might be thrown wrong. Many of the methods in OC that contain nserror parameters are not converted to Swift2.0, but the method declares a throw error (throws).


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

How to use Nserror in Swift

Related Article

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.