Learn Swift from scratch (Day 52)-Cocoa error handling mode

Source: Internet
Author: User

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.

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.